CCM NG: added Tests for StringUtils, and improved some of the methods of StringUtils

git-svn-id: https://svn.libreccm.org/ccm/ccm_ng@3522 8810af33-2d31-482b-a856-94f89814c4df
pull/2/head
konermann 2015-07-09 10:27:24 +00:00
parent dcee20be5b
commit e01c82e6c5
2 changed files with 861 additions and 383 deletions

View File

@ -13,7 +13,6 @@
* License along with this library; if not, write to the Free Software * License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/ */
package com.arsdigita.util; package com.arsdigita.util;
import java.io.PrintWriter; import java.io.PrintWriter;
@ -53,38 +52,41 @@ public class StringUtils {
public static final String NEW_LINE = System.getProperty("line.separator"); public static final String NEW_LINE = System.getProperty("line.separator");
private StringUtils() { private StringUtils() {
// can't instantiate me! // can't instantiate me!
} }
/** /**
* Tests if a string is empty. * Tests if a string is empty.
*
* @param s A string to test * @param s A string to test
* @return <code>true</code> if <code>s</code> is null or empty; * @return <code>true</code> if <code>s</code> is null or empty; otherwise
* otherwise <code>false</code> * <code>false</code>
*
*/ */
public static boolean emptyString(String s) { public static boolean emptyString(String s) {
boolean expr = (s == null || s.trim().length() == 0); if (s != null) {
return expr; return s.isEmpty();
}
return true;
} }
/** /**
* Tests if a string is empty. * Tests if a string is empty.
*
* @param o A string to test * @param o A string to test
* @return <code>true</code> if <code>o</code> is null or empty; * @return <code>true</code> if <code>o</code> is null or empty; otherwise
* otherwise <code>false</code> * <code>false</code>
*/ */
public static boolean emptyString(Object o) { public static boolean emptyString(Object o) {
boolean expr = boolean expr
(o == null || (o instanceof String && ((String)o).length() ==0)); = (o == null || (o instanceof String && ((String) o).length() == 0));
return expr; return expr;
} }
/** /**
* If the String is null, returns an empty string. Otherwise, * If the String is null, returns an empty string. Otherwise, returns the
* returns the string unaltered * string unaltered
*/ */
public static String nullToEmptyString(String s) { public static String nullToEmptyString(String s) {
return (s == null) ? "" : s; return (s == null) ? "" : s;
@ -93,80 +95,65 @@ public class StringUtils {
/** /**
* Escapes some "special" characters in HTML text (ampersand, angle * Escapes some "special" characters in HTML text (ampersand, angle
* brackets, quote). * brackets, quote).
*
* @param s The plain-text string to quote * @param s The plain-text string to quote
* @return The string with special characters escpaed. * @return The string with special characters escaped.
*/ */
public static String quoteHtml(String s) { public static String quoteHtml(String s) {
if (s != null) { if (s != null) {
StringBuffer result = new StringBuffer(s.length() + 10); s = s.replaceAll("&", "&amp;");
for (int i = 0; i < s.length(); i++) { s = s.replaceAll("\"", "&quot;");
char ch = s.charAt(i); s = s.replaceAll("<", "&lt;");
switch (ch) { s = s.replaceAll(">", "&gt;");
case '&': return s;
result.append("&amp;");
break;
case '"':
result.append("&quot;");
break;
case '<':
result.append("&lt;");
break;
case '>':
result.append("&gt;");
break;
default:
result.append(ch);
}
}
return result.toString();
} else { } else {
return ""; return "";
} }
} }
/** /**
* Takes a plaintext string, and returns an HTML string that, when * Takes a plaintext string, and returns an HTML string that, when rendered
* rendered by a web browser, will appear as the original input string * by a web browser, will appear as the original input string
* *
* @param s The input plaintext string * @param s The input plaintext string
* @return A HTML string with blank lines coverted to <pre>&lt;p></pre> * @return A HTML string with blank lines coverted to <pre>&lt;p></pre> and
* and ampersands/angle brackets escaped. * ampersands/angle brackets escaped.
*/ */
public static String textToHtml(String s) { public static String textToHtml(String s) {
s = quoteHtml(s); s = quoteHtml(s);
s = s_re.substitute("s/\r\n\r\n/<p>/g", s); s = s.replaceAll("\r\n\r\n", "<p>");
s = s_re.substitute("s/\n\n/<p>/g", s); s = s.replaceAll("\n\n", "<p>");
s = s_re.substitute("s/\r\r/<p>/g", s); s = s.replaceAll("\r\r", "<p>");
s = s_re.substitute("s/\r\n/<br>/g", s); s = s.replaceAll("\r\n", "<br>");
s = s_re.substitute("s/\n/<br>/g", s); s = s.replaceAll("\n", "<br>");
s = s_re.substitute("s/\r/<br>/g", s); s = s.replaceAll("\r", "<br>");
return s; return s;
} }
/** /**
* Removes tags and substitutes P tags with newlines. For much * Removes tags and substitutes P tags with newlines. For much more
* more extensive conversion of HTML fragments to plain text * extensive conversion of HTML fragments to plain text equivalents, see
* equivalents, see {@link HtmlToText}. * {@link HtmlToText}.
*/ */
public static String htmlToText(String s) { public static String htmlToText(String s) {
if (s != null) { if (s != null) {
// first take out new-lines // first take out new-lines
s = s_re.substitute("s/\n//g", s); s = s.replaceAll("\n", "");
s = s_re.substitute("s/\r//g", s); s = s.replaceAll("\r", "");
s = s_re.substitute("s/<[Pp]>/\n\n/g", s);
s = s_re.substitute("s/<br>/\n/ig", s); s = s.replaceAll("<[pP]>", "\n\n");
s = s.replaceAll("<br>", "\n");
// take out other tags // take out other tags
s = s_re.substitute("s/<([^>]*)>/ /g", s); s = s.replaceAll("<[^>]*>", " ");
return s; return s;
} else { } else {
return ""; return "";
} }
} }
/** /**
* Converts plain text with simple inline markup * Converts plain text with simple inline markup into HTML. The following
* into HTML. The following constructs are recognised: * constructs are recognised:
* *
* <ul> * <ul>
* <li>*text* generates bold <strong>text</strong> * <li>*text* generates bold <strong>text</strong>
@ -178,7 +165,8 @@ public class StringUtils {
* <a href="http://www.google.com">http://www.google.com</a> * <a href="http://www.google.com">http://www.google.com</a>
* <li>--- <br/>generates a horizontal line<br/> <hr/> * <li>--- <br/>generates a horizontal line<br/> <hr/>
* <li>___ <br/>generates a horizontal line<br/> <hr/> * <li>___ <br/>generates a horizontal line<br/> <hr/>
* <li><p>* my item <br> * <li><p>
* my item <br>
* * my next item<br> * * my next item<br>
* * my final item </p> * * my final item </p>
* generates an bulleted list * generates an bulleted list
@ -187,7 +175,8 @@ public class StringUtils {
* <li>my next item * <li>my next item
* <li>my final item * <li>my final item
* </ul> * </ul>
* <li><p>+ my item <br> * <li><p>
* + my item <br>
* + my next item<br> * + my next item<br>
* + my final item </p> * + my final item </p>
* generates an enumerated list * generates an enumerated list
@ -196,8 +185,8 @@ public class StringUtils {
* <li>my next item * <li>my next item
* <li>my final item * <li>my final item
* </ol> * </ol>
* <li>1/2, 1/4, 3/4, (C), (TM), (R) generate entities * <li>1/2, 1/4, 3/4, (C), (TM), (R) generate entities &frac12;, &frac14,
* &frac12;, &frac14, &frac34;, &copy; <sup>TM</sup> * &frac34;, &copy; <sup>TM</sup>
* &reg; * &reg;
* </ul> * </ul>
*/ */
@ -248,6 +237,7 @@ public class StringUtils {
} }
private static Map s_entities = new HashMap(); private static Map s_entities = new HashMap();
static { static {
s_log.debug("Static initalizer starting..."); s_log.debug("Static initalizer starting...");
s_entities.put("fraction12", "&frac12;"); s_entities.put("fraction12", "&frac12;");
@ -301,7 +291,6 @@ public class StringUtils {
s_log.debug("After links {" + s + "}"); s_log.debug("After links {" + s + "}");
} }
// Next lets process italics /italic/ // Next lets process italics /italic/
// NB. this must be first, otherwise closing tags </foo> // NB. this must be first, otherwise closing tags </foo>
// interfere with the pattern matching // interfere with the pattern matching
@ -326,7 +315,6 @@ public class StringUtils {
s_log.debug("After styles {" + s + "}"); s_log.debug("After styles {" + s + "}");
} }
// Links are next on the list @text(url) // Links are next on the list @text(url)
s = s_re.substitute("s|@@|\u0001|gx", s); s = s_re.substitute("s|@@|\u0001|gx", s);
s = s_re.substitute("s|@([^\\(@]+)\\(([^\\)]+)\\)|<a href=\"$2\">$1</a>|gx", s); s = s_re.substitute("s|@([^\\(@]+)\\(([^\\)]+)\\)|<a href=\"$2\">$1</a>|gx", s);
@ -385,6 +373,7 @@ public class StringUtils {
* *
*/ */
private static class TitledLinkSubstitution implements Substitution { private static class TitledLinkSubstitution implements Substitution {
private Map m_hash; private Map m_hash;
public TitledLinkSubstitution(Map hash) { public TitledLinkSubstitution(Map hash) {
@ -415,6 +404,7 @@ public class StringUtils {
* *
*/ */
private static class UntitledLinkSubstitution implements Substitution { private static class UntitledLinkSubstitution implements Substitution {
private Map m_hash; private Map m_hash;
public UntitledLinkSubstitution(Map hash) { public UntitledLinkSubstitution(Map hash) {
@ -433,8 +423,8 @@ public class StringUtils {
Integer i = m_hash.size(); Integer i = m_hash.size();
s_log.debug("Key: " + i); s_log.debug("Key: " + i);
m_hash.put(i, link); m_hash.put(i, link);
String dst = "@\u0002" + i.toString() + "\u0002(\u0002" + String dst = "@\u0002" + i.toString() + "\u0002(\u0002"
i.toString() + "\u0002)"; + i.toString() + "\u0002)";
appendBuffer.append(dst); appendBuffer.append(dst);
s_log.debug("Encoded Link: " + dst); s_log.debug("Encoded Link: " + dst);
} }
@ -444,6 +434,7 @@ public class StringUtils {
* *
*/ */
private static class UnobscureSubstitution implements Substitution { private static class UnobscureSubstitution implements Substitution {
private Map m_hash; private Map m_hash;
public UnobscureSubstitution(Map hash) { public UnobscureSubstitution(Map hash) {
@ -469,6 +460,7 @@ public class StringUtils {
* *
*/ */
private static class EntitySubstitution implements Substitution { private static class EntitySubstitution implements Substitution {
public void appendSubstitution(StringBuffer appendBuffer, public void appendSubstitution(StringBuffer appendBuffer,
MatchResult match, MatchResult match,
int substitutionCount, int substitutionCount,
@ -483,12 +475,11 @@ public class StringUtils {
} }
} }
/** /**
* Convert a string of items separated by a separator * Convert a string of items separated by a separator character to an
* character to an (string)array of the items. sep is the separator * (string)array of the items. sep is the separator character. Example:
* character. Example: Input - s == "cat,house,dog" sep==',' * Input - s == "cat,house,dog" sep==',' Output - {"cat", "house", "dog"}
* Output - {"cat", "house", "dog"} *
* @param s string contains items separated by a separator character. * @param s string contains items separated by a separator character.
* @param sep separator character. * @param sep separator character.
* @return Array of items. * @return Array of items.
@ -515,41 +506,47 @@ public class StringUtils {
} }
/** /**
* <p> Given a string, split it into substrings matching a regular * <p>
* expression that you supply. Parts of the original string which * Given a string, split it into substrings matching a regular expression
* don't match the regular expression also appear as substrings. The * that you supply. Parts of the original string which don't match the
* upshot of this is that the final substrings can be concatenated * regular expression also appear as substrings. The upshot of this is that
* to get the original string. </p> * the final substrings can be concatenated to get the original string. </p>
* *
* <p> As an example, let's say the original string is: </p> * <p>
* As an example, let's say the original string is: </p>
* *
* <pre> * <pre>
* s = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl"; * s = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl";
* </pre> * </pre>
* *
* <p> We call the function like this: </p> * <p>
* We call the function like this: </p>
* *
* <pre> * <pre>
* output = splitUp (s, "/::\\w+::/"); * output = splitUp (s, "/::\\w+::/");
* </pre> * </pre>
* *
* <p> The result (<code>output</code>) will be the following list: </p> * <p>
* The result (<code>output</code>) will be the following list: </p>
* *
* <pre> * <pre>
* ("/packages/foo/xsl/", "::vhost::", "/foo_", "::locale::", ".xsl") * ("/packages/foo/xsl/", "::vhost::", "/foo_", "::locale::", ".xsl")
* </pre> * </pre>
* *
* <p> Notice the important property that concatenating all these * <p>
* strings together will restore the original string. </p> * Notice the important property that concatenating all these strings
* together will restore the original string. </p>
* *
* <p> Here is another useful example. To split up HTML into elements * <p>
* and content, do: </p> * Here is another useful example. To split up HTML into elements and
* content, do: </p>
* *
* <pre> * <pre>
* output = splitUp (html, "/<.*?>/"); * output = splitUp (html, "/<.*?>/");
* </pre> * </pre>
* *
* <p> You will end up with something like this: </p> * <p>
* You will end up with something like this: </p>
* *
* <pre> * <pre>
* ("The following text will be ", "<b>", "bold", "</b>", ".") * ("The following text will be ", "<b>", "bold", "</b>", ".")
@ -562,12 +559,12 @@ public class StringUtils {
* *
* @author Richard W.M. Jones * @author Richard W.M. Jones
* *
* <p> This is equivalent to the Perl "global match in array context", * <p>
* This is equivalent to the Perl "global match in array context",
* specifically: <code>@a = /(RE)|(.+)/g;</code> </p> * specifically: <code>@a = /(RE)|(.+)/g;</code> </p>
* *
*/ */
public static List splitUp (String s, String re) public static List splitUp(String s, String re) {
{
Perl5Util p5 = new Perl5Util(); Perl5Util p5 = new Perl5Util();
ArrayList list = new ArrayList(); ArrayList list = new ArrayList();
@ -577,16 +574,16 @@ public class StringUtils {
MatchResult result = p5.getMatch(); MatchResult result = p5.getMatch();
// String up to the start of the match. // String up to the start of the match.
if (result.beginOffset (0) > 0) if (result.beginOffset(0) > 0) {
list.add(s.substring(0, result.beginOffset(0))); list.add(s.substring(0, result.beginOffset(0)));
}
// Matching part. // Matching part.
list.add(result.toString()); list.add(result.toString());
// Update s to be the remainder of the string. // Update s to be the remainder of the string.
s = s.substring(result.endOffset(0)); s = s.substring(result.endOffset(0));
} } else {
else {
// Finished. // Finished.
list.add(s); list.add(s);
@ -598,10 +595,9 @@ public class StringUtils {
} }
/** /**
* Converts an array of Strings into a single String separated by * Converts an array of Strings into a single String separated by a given
* a given character. * character. Example Input: {"cat", "house", "dog"}, ',' Output -
* Example Input: {"cat", "house", "dog"}, ',' * "cat,house,dog"
* Output - "cat,house,dog"
* *
* @param strings The string array too join. * @param strings The string array too join.
* @param joinChar The character to join the array members together. * @param joinChar The character to join the array members together.
@ -624,10 +620,9 @@ public class StringUtils {
} }
/** /**
* Converts an array of Strings into a single String separated by * Converts an array of Strings into a single String separated by a given
* a given string. * string. Example Input: {"cat", "house", "dog"}, ", " Output - "cat,
* Example Input: {"cat", "house", "dog"}, ", " * house, dog"
* Output - "cat, house, dog"
* *
* @param strings The string array too join. * @param strings The string array too join.
* @param joinStr The string to join the array members together. * @param joinStr The string to join the array members together.
@ -651,24 +646,20 @@ public class StringUtils {
/** /**
* Extract a parameter value from a packed list of parameter values. * Extract a parameter value from a packed list of parameter values.
* Example: * Example: input: key="age", sep=',', plist="cost=23,age=27,name=Thom"
* input: key="age", sep=',', * output = "27". This is a simple implementation that is meant for
* plist="cost=23,age=27,name=Thom" * controlled use in which the key and values are known to be safe.
* output = "27". * Specifically, the equals character must be used to indicate parameter
* This is a simple implementation that is meant for controlled use in which * assignments. There is no escape character. Thus the parameter names and
* the key and values are known to be safe. * values cannot contain the equals character or the separator character.
* Specifically, the equals character must be used to indicate
* parameter assignments. There is no escape character. Thus the
* parameter names and values cannot contain the equals character or the
* separator character.
* *
* @param key the key indicating which parameter value to extract. * @param key the key indicating which parameter value to extract.
* @param plist packed list of key=value assignments. The character '=' * @param plist packed list of key=value assignments. The character '=' must
* must be used to indicate the assignment. * be used to indicate the assignment.
* @param sep separator character. * @param sep separator character.
* @return the value corresponding to the key, or null if the key is not * @return the value corresponding to the key, or null if the key is not
* present. If the key appears in the list more than once, * present. If the key appears in the list more than once, the first value
* the first value is returned. * is returned.
*/ */
public static String getParameter(String key, String plist, char sep) { public static String getParameter(String key, String plist, char sep) {
int key_end; int key_end;
@ -680,8 +671,8 @@ public class StringUtils {
return null; // Did not find key return null; // Did not find key
} }
key_end = key_start + key.length(); key_end = key_start + key.length();
if (plist.charAt(key_end) == '=' && if (plist.charAt(key_end) == '='
(key_start == 0 || plist.charAt(key_start - 1) == sep)) { && (key_start == 0 || plist.charAt(key_start - 1) == sep)) {
// Found isolated parameter value, this is the match // Found isolated parameter value, this is the match
int value_end = plist.indexOf(sep, key_end); int value_end = plist.indexOf(sep, key_end);
if (value_end == -1) { if (value_end == -1) {
@ -701,13 +692,14 @@ public class StringUtils {
/** /**
* Strip extra white space from a string. This replaces any white space * Strip extra white space from a string. This replaces any white space
* character or consecutive white space characters with a single space. * character or consecutive white space characters with a single space. It
* It is useful when comparing strings that should be equal except for * is useful when comparing strings that should be equal except for possible
* possible differences in white space. Example: input = "I \ndo\tsee". * differences in white space. Example: input = "I \ndo\tsee". Output = "I
* Output = "I do see". * do see".
*
* @param s string that may contain extra white space * @param s string that may contain extra white space
* @return string the same as the input, but with extra white space * @return string the same as the input, but with extra white space removed
* removed and replaced by a single space. * and replaced by a single space.
*/ */
static public String stripWhiteSpace(String s) { static public String stripWhiteSpace(String s) {
StringBuffer to = new StringBuffer(); StringBuffer to = new StringBuffer();
@ -729,8 +721,8 @@ public class StringUtils {
} }
/** /**
* Get a String representation for an Object. If it has an * Get a String representation for an Object. If it has an asString method,
* asString method, use that; otherwise fall back on toString * use that; otherwise fall back on toString
*/ */
public static String toString(Object o) { public static String toString(Object o) {
try { try {
@ -739,14 +731,13 @@ public class StringUtils {
} catch (NoSuchMethodException e) { } catch (NoSuchMethodException e) {
return o.toString(); return o.toString();
} catch (Exception e) { } catch (Exception e) {
throw new UncheckedWrapperException throw new UncheckedWrapperException("Invoking asString() on an " + o.getClass(), e);
("Invoking asString() on an " + o.getClass(), e);
} }
} }
/** /**
* create a String representation of a map. This method is not * create a String representation of a map. This method is not too
* too necessary, because Map.toString() does almost the same. * necessary, because Map.toString() does almost the same.
*/ */
public static String toString(Map m) { public static String toString(Map m) {
StringBuffer to = new StringBuffer(); StringBuffer to = new StringBuffer();
@ -784,9 +775,9 @@ public class StringUtils {
/** /**
* Strips all new-line characters from the input string. * Strips all new-line characters from the input string.
*
* @param str a string to strip * @param str a string to strip
* @return the input string with all new-line characters * @return the input string with all new-line characters removed.
* removed.
* @post result.indexOf('\r') == 0 * @post result.indexOf('\r') == 0
* @post result.indexOf('\n') == 0 * @post result.indexOf('\n') == 0
*/ */
@ -803,9 +794,11 @@ public class StringUtils {
} }
/** /**
* <p>Add a possible newline for proper wrapping.</p> * <p>
* Add a possible newline for proper wrapping.</p>
* *
* <p>Checks the given String to see if it ends with whitspace. If so, it * <p>
* Checks the given String to see if it ends with whitspace. If so, it
* assumes this whitespace is intentional formatting and returns a reference * assumes this whitespace is intentional formatting and returns a reference
* to the original string. If not, a new <code>String</code> object is * to the original string. If not, a new <code>String</code> object is
* created containing the original plus a platform-dependent newline * created containing the original plus a platform-dependent newline
@ -823,27 +816,22 @@ public class StringUtils {
} }
} }
/** /**
* This takes the passed in string and truncates it. * This takes the passed in string and truncates it. It cuts the string off
* It cuts the string off at the length specified and then * at the length specified and then goes back to the most recent space and
* goes back to the most recent space and truncates any * truncates any word that may have been cut off. It also takes the string
* word that may have been cut off. It also takes the * and converts it to plain text so that no HTML will be shown.
* string and converts it to plain text so that no HTML
* will be shown.
*/ */
public static String truncateString(String s, int length) { public static String truncateString(String s, int length) {
return truncateString(s, length, true); return truncateString(s, length, true);
} }
/** /**
* This takes the passed in string and truncates it. * This takes the passed in string and truncates it. It cuts the string off
* It cuts the string off at the length specified and then * at the length specified and then goes back to the most recent space and
* goes back to the most recent space and truncates any * truncates any word that may have been cut off. The htmlToText dictates
* word that may have been cut off. The htmlToText dictates * whehter or not the string should be converted from HTML to text before
* whehter or not the string should be converted from HTML to * being truncated
* text before being truncated
* *
* @param s The string to be truncated * @param s The string to be truncated
* @param length The length which to truncate the string * @param length The length which to truncate the string
@ -864,13 +852,18 @@ public class StringUtils {
return string; return string;
} }
return string.substring(0, string.lastIndexOf(" ", length)); if (string.lastIndexOf(" ", length) == -1) {
//no whitespace found, so truncate at the specified length even if
// it is in the middle of a word
return string.substring(0, length);
} }
return string.substring(0, string.lastIndexOf(" ", length)).trim();
}
/** /**
* "join" a List of Strings into a single string, with each string * "join" a List of Strings into a single string, with each string separated
* separated by a defined separator string. * by a defined separator string.
* *
* @param elements the strings to join together * @param elements the strings to join together
* @param sep the separator string * @param sep the separator string
@ -897,9 +890,8 @@ public class StringUtils {
} }
/** /**
* Removes whitespace from the beginning of a string. If the * Removes whitespace from the beginning of a string. If the string consists
* string consists of nothing but whitespace characters, an empty * of nothing but whitespace characters, an empty string is returned.
* string is returned.
*/ */
public final static String trimleft(String s) { public final static String trimleft(String s) {
for (int i = 0; i < s.length(); i++) { for (int i = 0; i < s.length(); i++) {
@ -911,8 +903,8 @@ public class StringUtils {
} }
/** /**
* Returns a String containing the specified repeat count of a * Returns a String containing the specified repeat count of a given pattern
* given pattern String. * String.
* *
* @param pattern the pattern String * @param pattern the pattern String
* @param repeatCount the number of time to repeat it * @param repeatCount the number of time to repeat it
@ -926,8 +918,8 @@ public class StringUtils {
} }
/** /**
* Returns a String containing the specified repeat count of a * Returns a String containing the specified repeat count of a given pattern
* given pattern character. * character.
* *
* @param pattern the pattern character * @param pattern the pattern character
* @param repeatCount the number of time to repeat it * @param repeatCount the number of time to repeat it
@ -937,9 +929,9 @@ public class StringUtils {
} }
/** /**
* Wrap a string to be no wider than 80 characters. This is just * Wrap a string to be no wider than 80 characters. This is just a
* a convenience method for calling the more general method with a * convenience method for calling the more general method with a default
* default string width. * string width.
* *
* @param input the String to wrap * @param input the String to wrap
* *
@ -950,25 +942,23 @@ public class StringUtils {
} }
/** /**
* Wrap a string to be no wider than a specified number of * Wrap a string to be no wider than a specified number of characters by
* characters by inserting line breaks. If the input is null or * inserting line breaks. If the input is null or the empty string, a string
* the empty string, a string consisting of only the newline * consisting of only the newline character will be returned. Otherwise the
* character will be returned. Otherwise the input string will be * input string will be wrapped to the specified line length. In all cases
* wrapped to the specified line length. In all cases the last * the last character of the return value will be a single newline.
* character of the return value will be a single newline.
* *
* <p>Notes: * <p>
* Notes:
* *
* <ol> * <ol>
* <li>line breaks in the input string are preserved * <li>line breaks in the input string are preserved
* <li>wrapping is "soft" in that lines in the output string may * <li>wrapping is "soft" in that lines in the output string may be longer
* be longer than maxLength if they consist of contiguous * than maxLength if they consist of contiguous non-whitespace characters.
* non-whitespace characters.
* </ol> * </ol>
* *
* @param input the String to wrap * @param input the String to wrap
* @param maxLength the maximum number of characters between line * @param maxLength the maximum number of characters between line breaks
* breaks
* *
* @since 5.1.2 * @since 5.1.2
*/ */
@ -980,7 +970,6 @@ public class StringUtils {
// Make sure that we start with a string terminated by a // Make sure that we start with a string terminated by a
// newline character. Some of the index calculations below // newline character. Some of the index calculations below
// depend on this. // depend on this.
if (emptyString(input)) { if (emptyString(input)) {
return String.valueOf(ENDL); return String.valueOf(ENDL);
} else { } else {
@ -993,8 +982,7 @@ public class StringUtils {
while (startOfLine < input.length()) { while (startOfLine < input.length()) {
String line = input.substring String line = input.substring(startOfLine, Math.min(input.length(),
(startOfLine, Math.min(input.length(),
startOfLine + maxLength)); startOfLine + maxLength));
if (line.equals("")) { if (line.equals("")) {
@ -1005,8 +993,7 @@ public class StringUtils {
if (firstNewLine != -1) { if (firstNewLine != -1) {
// there is a newline // there is a newline
output.append output.append(input.substring(startOfLine,
(input.substring(startOfLine,
startOfLine + firstNewLine)); startOfLine + firstNewLine));
output.append(ENDL); output.append(ENDL);
startOfLine += firstNewLine + 1; startOfLine += firstNewLine + 1;
@ -1017,7 +1004,6 @@ public class StringUtils {
// we're on the last line and it is < maxLength so // we're on the last line and it is < maxLength so
// just return it // just return it
output.append(line); output.append(line);
break; break;
} }
@ -1027,17 +1013,13 @@ public class StringUtils {
// no space found! Try the first space in the whole // no space found! Try the first space in the whole
// rest of the string // rest of the string
int nextSpace = input.indexOf(SPACE, startOfLine);
int nextSpace = input.indexOf int nextNewLine = input.indexOf(ENDL, startOfLine);
(SPACE, startOfLine);
int nextNewLine = input.indexOf
(ENDL, startOfLine);
if (nextSpace == -1) { if (nextSpace == -1) {
lastSpace = nextNewLine; lastSpace = nextNewLine;
} else { } else {
lastSpace = Math.min lastSpace = Math.min(nextSpace, nextNewLine);
(nextSpace,nextNewLine);
} }
if (lastSpace == -1) { if (lastSpace == -1) {
@ -1048,12 +1030,10 @@ public class StringUtils {
} }
// code below will add this to the start of the line // code below will add this to the start of the line
lastSpace -= startOfLine; lastSpace -= startOfLine;
} }
// append up to the last space // append up to the last space
output.append(input.substring(startOfLine, output.append(input.substring(startOfLine,
startOfLine + lastSpace)); startOfLine + lastSpace));
output.append(ENDL); output.append(ENDL);
@ -1072,27 +1052,17 @@ public class StringUtils {
* @return true if value is alphanumeric, false otherwise. * @return true if value is alphanumeric, false otherwise.
*/ */
public static boolean isAlphaNumeric(String value) { public static boolean isAlphaNumeric(String value) {
for (int i = 0; i < value.length(); i++) { return !value.matches("^.*[^a-zA-Z0-9 ].*$");
char c = value.charAt(i);
if (!(('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') ||
('0' <= c && c <= '9'))) {
return false;
}
}
return true;
} }
/** /**
* This method performs interpolation on multiple variables. * This method performs interpolation on multiple variables. The keys in the
* The keys in the hash table correspond directly to the placeholders * hash table correspond directly to the placeholders in the string. The
* in the string. The values in the hash table can either be * values in the hash table can either be plain strings, or an instance of
* plain strings, or an instance of the PlaceholderValueGenerator * the PlaceholderValueGenerator interface
* interface
* *
* Variable placeholders are indicated in text by surrounding * Variable placeholders are indicated in text by surrounding a key word
* a key word with a pair of colons. The keys in the hash * with a pair of colons. The keys in the hash table correspond to the names
* table correspond to the names
* *
* eg. "::forename:: has the email address ::email::" * eg. "::forename:: has the email address ::email::"
* *
@ -1121,11 +1091,9 @@ public class StringUtils {
return result.toString(); return result.toString();
} }
/** /**
* THis method performs a single variable substitution * THis method performs a single variable substitution on a string. The
* on a string. The placeholder takes the form of * placeholder takes the form of ::key:: within the sample text.
* ::key:: within the sample text.
* *
* @see java.text.MessageFormat * @see java.text.MessageFormat
* *
@ -1139,8 +1107,6 @@ public class StringUtils {
return s_re.substitute(pattern, text); return s_re.substitute(pattern, text);
} }
/** /**
* Finds all occurrences of <code>find</code> in <code>str</code> and * Finds all occurrences of <code>find</code> in <code>str</code> and
* replaces them with them with <code>replace</code>. * replaces them with them with <code>replace</code>.
@ -1155,16 +1121,20 @@ public class StringUtils {
Assert.exists(find, String.class); Assert.exists(find, String.class);
Assert.exists(replace, String.class); Assert.exists(replace, String.class);
if ( str == null ) return null; if (str == null) {
return null;
}
int cur = str.indexOf(find); int cur = str.indexOf(find);
if ( cur < 0 ) return str; if (cur < 0) {
return str;
}
final int findLength = find.length(); final int findLength = find.length();
// If replace is longer than find, assume the result is going to be // If replace is longer than find, assume the result is going to be
// slightly longer than the original string. // slightly longer than the original string.
final int bufferLength = final int bufferLength
replace.length() > findLength ? (int) (str.length() * 1.1) : str.length(); = replace.length() > findLength ? (int) (str.length() * 1.1) : str.length();
StringBuffer sb = new StringBuffer(bufferLength); StringBuffer sb = new StringBuffer(bufferLength);
int last = 0; int last = 0;
@ -1187,27 +1157,25 @@ public class StringUtils {
return sb.toString(); return sb.toString();
} }
/** /**
* An interface allowing the value for a placeholder to be * An interface allowing the value for a placeholder to be dynamically
* dynamically generated. * generated.
*/ */
public interface PlaceholderValueGenerator { public interface PlaceholderValueGenerator {
/** /**
* Returns the value corresponding to the supplied key * Returns the value corresponding to the supplied key placeholder.
* placeholder.
* *
* @param key the key being substituted * @param key the key being substituted
*/ */
public String generate(String key); public String generate(String key);
} }
/** /**
* *
*/ */
private static class HashSubstitution implements Substitution { private static class HashSubstitution implements Substitution {
private Map m_hash; private Map m_hash;
public HashSubstitution(Map hash) { public HashSubstitution(Map hash) {
@ -1223,9 +1191,9 @@ public class StringUtils {
String placeholder = match.toString(); String placeholder = match.toString();
String key = placeholder.substring(2, placeholder.length() - 2); String key = placeholder.substring(2, placeholder.length() - 2);
Object value = (m_hash.containsKey(key) ? Object value = (m_hash.containsKey(key)
m_hash.get(key) : ? m_hash.get(key)
placeholder); : placeholder);
if (s_log.isDebugEnabled()) { if (s_log.isDebugEnabled()) {
Object hashValue = m_hash.get(key); Object hashValue = m_hash.get(key);
@ -1233,13 +1201,13 @@ public class StringUtils {
s_log.debug("Placeholder: " + placeholder); s_log.debug("Placeholder: " + placeholder);
s_log.debug("Key: " + key); s_log.debug("Key: " + key);
if (null != value) { if (null != value) {
s_log.debug( "Value (" + value.getClass().getName() + s_log.debug("Value (" + value.getClass().getName()
"): " + value.toString() ); + "): " + value.toString());
} }
if (null != hashValue) { if (null != hashValue) {
s_log.debug( "Hash Value (" + s_log.debug("Hash Value ("
hashValue.getClass().getName() + "): " + + hashValue.getClass().getName() + "): "
hashValue.toString() ); + hashValue.toString());
} }
} }
@ -1273,7 +1241,9 @@ public class StringUtils {
* @throws NullPointerException if <code>throwable</code> is null * @throws NullPointerException if <code>throwable</code> is null
*/ */
public static String getStackTrace(Throwable throwable) { public static String getStackTrace(Throwable throwable) {
if (throwable==null) { throw new NullPointerException("throwable"); } if (throwable == null) {
throw new NullPointerException("throwable");
}
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw); PrintWriter pw = new PrintWriter(sw);
@ -1283,10 +1253,11 @@ public class StringUtils {
} }
/** /**
* Returns a list of lines where each line represents one level * Returns a list of lines where each line represents one level in the stack
* in the stack trace captured by <code>throwable</code>. * trace captured by <code>throwable</code>.
* *
* <p>For a stack trace like this:</p> * <p>
* For a stack trace like this:</p>
* *
* <pre> * <pre>
* java.lang.Throwable * java.lang.Throwable
@ -1296,7 +1267,8 @@ public class StringUtils {
* at Main.main(Main.java:7) * at Main.main(Main.java:7)
* </pre> * </pre>
* *
* <p>the returned list looks like this: </p> * <p>
* the returned list looks like this: </p>
* *
* <pre> * <pre>
* ["java.lang.Throwable", * ["java.lang.Throwable",
@ -1310,12 +1282,13 @@ public class StringUtils {
* @throws NullPointerException if <code>throwable</code> is null * @throws NullPointerException if <code>throwable</code> is null
*/ */
public static List getStackList(Throwable throwable) { public static List getStackList(Throwable throwable) {
StringTokenizer tkn = new StringTokenizer StringTokenizer tkn = new StringTokenizer(getStackTrace(throwable), System.getProperty("line.separator"));
(getStackTrace(throwable), System.getProperty("line.separator"));
List list = new LinkedList(); List list = new LinkedList();
while (tkn.hasMoreTokens()) { while (tkn.hasMoreTokens()) {
String token = tkn.nextToken().trim(); String token = tkn.nextToken().trim();
if ( "".equals(token) ) { continue; } if ("".equals(token)) {
continue;
}
if (token.startsWith("at ")) { if (token.startsWith("at ")) {
list.add(token.substring(3)); list.add(token.substring(3));
} else { } else {
@ -1333,9 +1306,9 @@ public class StringUtils {
* For example, "<code>Business promotions!</code>" will be converted to * For example, "<code>Business promotions!</code>" will be converted to
* "<code>business-promotions</code>". * "<code>business-promotions</code>".
* *
* @param name * @param name the to be converted into a URL.
* the to be converted into a URL. * @return the converted name, possibly unchanged and null if the input is
* @return the converted name, possibly unchanged and null if the input is null. * null.
*/ */
public static String urlize(String name) { public static String urlize(String name) {
if (name == null) { if (name == null) {
@ -1348,16 +1321,12 @@ public class StringUtils {
if (Character.isLetter(ch)) { if (Character.isLetter(ch)) {
urlizedName.append(Character.toLowerCase(ch)); urlizedName.append(Character.toLowerCase(ch));
} } else if (Character.isDigit(ch) || ch == '_' || ch == '-') {
else if (Character.isDigit(ch) || ch == '_' || ch == '-') {
urlizedName.append(ch); urlizedName.append(ch);
} } else if (ch == ' ' || ch == '&' || ch == '/') {
else if (ch == ' ' || ch == '&' || ch == '/') {
urlizedName.append('-'); urlizedName.append('-');
} }
} }
return urlizedName.toString(); return urlizedName.toString();
} }
} }

View File

@ -0,0 +1,509 @@
/*
* Copyright (C) 2015 LibreCCM Foundation.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package com.arsdigita.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertTrue;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.libreccm.tests.categories.UnitTest;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
/**
*
* @author Konermann
*/
@Category(UnitTest.class)
public class StringUtilsTest {
public StringUtilsTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
// @Test(expected = AssertionError.class)
// public void checkFailMessage() {
// Assert.fail("errormessage");
// }
@Test
public void testSmartText() {
String src = "foo *bar* wibble /eek/\n"
+ "and mailto:dan@berrange.com eek!\n"
+ "\n"
+ "the second =paragraph= contains\n"
+ "a link to http://www.google.com\n"
+ "and the fractions 1/2 3/4 1/4 and\n"
+ "the symbols for copyright (C),\n"
+ "trademark (TM) and rights (R)\n"
+ "\n"
+ "* a bullet list\n"
+ "* more *bullets* in\n"
+ " this list element\n"
+ "* a final element\n"
+ "\n"
+ "-------\n"
+ "\n"
+ "+ now an enumerated list item\n"
+ "+ and one /more/\n"
+ "+ this one is split over two lines\n"
+ "for testing purposes\n"
+ "\n"
+ "___\n"
+ "\n"
+ "and now the end is near, lets test\n"
+ "@google(http://www.google.com) a few\n"
+ "titled links, including a mailto\n"
+ "@Dan B(mailto:dan@@berrange.com)";
String expected = "<div>\n"
+ "foo <strong>bar</strong> wibble <em>eek</em>\n"
+ "and <a href=\"mailto:dan@berrange.com\">mailto:dan@berrange.com</a> eek!\n"
+ "</div>\n"
+ "\n"
+ "<div>\n"
+ "the second <code>paragraph</code> contains\n"
+ "a link to <a href=\"http://www.google.com\">http://www.google.com</a>\n"
+ "and the fractions &frac12; &frac34; &frac14; and\n"
+ "the symbols for copyright &copy;,\n"
+ "trademark <sup>TM</sup> and rights &reg;\n"
+ "</div>\n"
+ "\n"
+ "<ul>\n"
+ "<li>\n"
+ "a bullet list\n"
+ "</li>\n"
+ "<li>\n"
+ "more <strong>bullets</strong> in\n"
+ " this list element\n"
+ "</li>\n"
+ "<li>\n"
+ "a final element</li>\n"
+ "</ul>\n"
+ "\n"
+ "<hr/>\n"
+ "\n"
+ "<ol>\n"
+ "<li>\n"
+ "now an enumerated list item\n"
+ "</li>\n"
+ "<li>\n"
+ "and one <em>more</em>\n"
+ "</li>\n"
+ "<li>\n"
+ "this one is split over two lines\n"
+ "for testing purposes</li>\n"
+ "</ol>\n"
+ "\n"
+ "<hr/>\n"
+ "\n"
+ "<div>\n"
+ "and now the end is near, lets test\n"
+ "<a href=\"http://www.google.com\">google</a> a few\n"
+ "titled links, including a mailto\n"
+ "<a href=\"mailto:dan@berrange.com\">Dan B</a>\n"
+ "</div>\n";
String actual = StringUtils.smartTextToHtml(src);
assertTrue(expected.equals(actual));
}
@Test
public void testEmptyString() {
assertTrue(StringUtils.emptyString(null));
assertTrue(StringUtils.emptyString(""));
assertTrue(StringUtils.emptyString((Object) ""));
assertTrue(!StringUtils.emptyString("foo"));
assertTrue(!StringUtils.emptyString((Object) "foo"));
assertTrue(!StringUtils.emptyString((Object) (new Integer(1))));
}
@Test
public void testQuoteHtml() {
assertEquals("", StringUtils.quoteHtml(null));
assertEquals("", StringUtils.quoteHtml(""));
assertEquals("foo", StringUtils.quoteHtml("foo"));
assertEquals("foo&amp;", StringUtils.quoteHtml("foo&"));
assertEquals("&amp;foo", StringUtils.quoteHtml("&foo"));
assertEquals("&amp;foo&amp;", StringUtils.quoteHtml("&foo&"));
assertEquals("&amp;&quot;&lt;&gt;&quot;&amp;",
StringUtils.quoteHtml("&\"<>\"&"));
}
@Test
public void testGetParameter() throws Exception {
String plist = "boyspet=play,pet=dog,play=yes,age=34,eopt=,opt=23";
verifyGet(plist, "boyspet", "play");
verifyGet(plist, "pet", "dog");
verifyGet(plist, "play", "yes");
verifyGet(plist, "age", "34");
verifyGet(plist, "eopt", "");
verifyGet(plist, "opt", "23");
verifyGet(plist, "spet", null);
verifyGet(plist, "notin", null);
}
// helper method for above test.
private static void verifyGet(String plist, String key, String expected) {
String found = StringUtils.getParameter(key, plist, ',');
assertEquals("Expected parameter not found, key=" + key
+ " expected=" + expected + " found=" + found,
expected, found);
}
@Test
public void testSplit() throws Exception {
String plist = "cat,hat,,bat,rat";
String[] ar = StringUtils.split(plist, ',');
verifySplit("cat", ar[0]);
verifySplit("hat", ar[1]);
verifySplit("", ar[2]);
verifySplit("bat", ar[3]);
verifySplit("rat", ar[4]);
assertEquals("expected array length 5, found="
+ ar.length, ar.length, 5);
plist = ",,dog,fish,,,";
ar = StringUtils.split(plist, ',');
verifySplit("", ar[0]);
verifySplit("", ar[1]);
verifySplit("dog", ar[2]);
verifySplit("fish", ar[3]);
verifySplit("", ar[4]);
verifySplit("", ar[5]);
verifySplit("", ar[6]);
assertEquals("expected array length 7, found="
+ ar.length, ar.length, 7);
}
// helper method for above test.
private void verifySplit(String expected, String found) {
String errMsg = "Split, expected = " + expected
+ " found = " + found;
assertEquals(errMsg, expected, found);
}
@Test
public void testJoinChar() {
String[] input = {"foo", "bar", "Qux"};
String expected = "foo,bar,Qux";
String found = StringUtils.join(input, ',');
String errMsg = "join char, expected = " + expected
+ " found = " + found;
assertEquals(errMsg, expected, found);
}
@Test
public void testJoinString() {
String[] input = {"foo", "bar", "Qux"};
String expected = "foo,bar,Qux";
String found = StringUtils.join(input, ",");
String errMsg = "join string, expected = " + expected
+ " found = " + found;
assertEquals(errMsg, expected, found);
}
@Test
public void testStripWhiteSpace() throws Exception {
String in = " < H> e \t\n ll/> o . \n ";
String expected_out = "< H> e ll/> o .";
String actual_out = StringUtils.stripWhiteSpace(in);
assertEquals("stripWhiteSpace failed. Expected = '"
+ expected_out + "', Found = '" + actual_out + "'",
expected_out, actual_out);
}
@Test
public void testAddNewline() throws Exception {
String in = "*";
String nl = System.getProperty("line.separator");
String expected_out = in + nl;
String actual_out = StringUtils.addNewline(in);
assertEquals("failed to add newline", expected_out, actual_out);
in = "* ";
expected_out = in;
actual_out = StringUtils.addNewline(in);
assertEquals("added unecessary newline", expected_out, actual_out);
in = "*" + nl;
expected_out = in;
actual_out = StringUtils.addNewline(in);
assertEquals("added unecessary newline", expected_out, actual_out);
in = "" + nl;
expected_out = in;
actual_out = StringUtils.addNewline(in);
assertEquals("added unecessary newline", expected_out, actual_out);
}
@Test
public void testHtmlToText() {
String in = "<p>this is the text<br>newline .</p>one<br><b>two</b><br>";
String expected_out = "\n\nthis is the text\nnewline . one\n two \n";
String actual_out = StringUtils.htmlToText(in);
String errMsg = "htmlToText, expected = " + expected_out
+ " found = " + actual_out;
assertEquals(errMsg, expected_out, actual_out);
in = "Text with <a <b <c > strange markup";
expected_out = "Text with strange markup";
actual_out = StringUtils.htmlToText(in);
errMsg = "htmlToText, expected = " + expected_out
+ " found = " + actual_out;
assertEquals(errMsg,expected_out, actual_out);
}
@Test
public void testTrimleft() {
String in = "a";
String expected_out = "a";
String actual_out = StringUtils.trimleft(in);
assertEquals("trimleft invalid", expected_out, actual_out);
in = " a";
expected_out = "a";
actual_out = StringUtils.trimleft(in);
assertEquals("trimleft invalid", expected_out, actual_out);
in = " ";
expected_out = "";
actual_out = StringUtils.trimleft(in);
assertEquals("trimleft invalid", expected_out, actual_out);
}
@Test
public void testRepeat() {
String in = "a";
String expected_out = "aaaaa";
String actual_out = StringUtils.repeat(in, 5);
assertEquals("repeat invalid", expected_out, actual_out);
actual_out = StringUtils.repeat('a', 5);
assertEquals("repeat invalid", expected_out, actual_out);
}
@Test
public void testWrap() {
// Identity test
String in = "a\n";
String expected_out = in;
String actual_out = StringUtils.wrap(in);
assertEquals("wrap failed identify test",
expected_out,
actual_out);
// Identify test with multiple words
in = "a b c d e\n";
expected_out = in;
actual_out = StringUtils.wrap(in);
assertEquals("wrap failed identify test",
expected_out,
actual_out);
// Simple test with short lines
in = StringUtils.repeat("1234 ", 5);
expected_out = StringUtils.repeat("1234\n", 5);
actual_out = StringUtils.wrap(in, 1);
assertEquals("wrap invalid",
expected_out,
actual_out);
// Verify preservation of line breaks
in = StringUtils.repeat("1234\n", 5);
expected_out = in;
actual_out = StringUtils.wrap(in, 100);
assertEquals("line break preservation failed",
expected_out,
actual_out);
// Verify a "standard" wrapping case
in = StringUtils.repeat("1234 ", 10);
expected_out
= StringUtils.repeat("1234 ", 5).trim() + "\n"
+ StringUtils.repeat("1234 ", 5).trim() + "\n";
actual_out = StringUtils.wrap(in, 25);
assertEquals("line wrapping failed",
expected_out,
actual_out);
}
@Test
public void testPlaceholders() {
String in = "foo ::bar:: wizz";
String expected_out = "foo eek wizz";
String actual_out = StringUtils.interpolate(in, "bar", "eek");
assertEquals("interpolate failed simple placeholder",
expected_out,
actual_out);
HashMap vars = new HashMap();
vars.put("bar", "eek");
vars.put("more", "wibble");
in = "foo ::bar:: wizz ::more:: done";
expected_out = "foo eek wizz wibble done";
actual_out = StringUtils.interpolate(in, vars);
assertEquals("interpolate failed hashmap test",
expected_out,
actual_out);
}
@Test
public void testReplace() {
String[] pairs = {null, null,
"foobar", "foobar",
";foobar", "\\;foobar",
";foo;bar;baz", "\\;foo\\;bar\\;baz",
";;foobar", "\\;\\;foobar",
"f;o;obar", "f\\;o\\;obar",
"f;o;;bar", "f\\;o\\;\\;bar",
"foobar;", "foobar\\;",
"foobar;;", "foobar\\;\\;"};
for (int ii = 0, jj = 1; jj < pairs.length; ii += 2, jj += 2) {
System.err.println("ii=" + ii + ", pairs[ii]=" + pairs[ii]
+ ", jj=" + jj + ", pairs[jj]=" + pairs[jj]);
String expected = pairs[jj];
String actual = StringUtils.replace(pairs[ii], ";", "\\;");
assertEquals(expected, actual);
expected = pairs[ii];
actual = StringUtils.replace(pairs[jj], "\\;", ";");
assertEquals(expected, actual);
}
}
@Test
public void testUrlize() {
assertEquals(null, StringUtils.urlize(null));
assertEquals("", StringUtils.urlize(""));
assertEquals("-", StringUtils.urlize(" "));
assertEquals("----", StringUtils.urlize(" "));
assertEquals("abc-def", StringUtils.urlize("ABC DEF"));
assertEquals("-abc-def-", StringUtils.urlize(" ABC DEF "));
assertEquals("0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz-_---", StringUtils.urlize("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_ &/"));
assertEquals("helpaplawsorg", StringUtils.urlize("help@aplaws.org"));
}
@Test
public void testIsAlphaNumeric() {
assertTrue(StringUtils.isAlphaNumeric("foo"));
assertTrue(StringUtils.isAlphaNumeric("123"));
assertTrue(StringUtils.isAlphaNumeric("bar778"));
assertFalse(StringUtils.isAlphaNumeric("foo/bar"));
assertFalse(StringUtils.isAlphaNumeric("&"));
}
@Test
public void testTruncateString() {
assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 8, true), is("Lorem"));
assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 2, true), is("Lo"));
assertThat(StringUtils.truncateString(null, 2, true), is(""));
assertThat(StringUtils.truncateString("Lorem <b> ipsum </b> dolor sit amet", 12, true), is("Lorem"));
assertThat(StringUtils.truncateString("Lorem <b> ipsum </b> dolor sit amet", 12, false), is("Lorem <b>"));
assertThat(StringUtils.truncateString("Lorem ipsum dolor sit amet", 99, true), is("Lorem ipsum dolor sit amet"));
}
@Test
public void testJoinElements() {
List<String> input = new ArrayList<>();
input.add("foo");
input.add("bar");
input.add("Qux");
String expected = "foo,bar,Qux";
String found = StringUtils.join(input, ",");
String errMsg = "join Elements, expected = " + expected
+ " found = " + found;
assertEquals(errMsg, expected, found);
}
@Test(expected = NullPointerException.class)
public void testIfGetStackTraceFails() {
StringUtils.getStackTrace(null);
}
@Test
public void testStripNewLines() {
assertEquals(StringUtils.stripNewLines("line1\nline2"), "line1line2");
assertEquals(StringUtils.stripNewLines("Lorem ipsum dolor sit amet"), "Lorem ipsum dolor sit amet");
}
@Test
public void testNullToEmptyString() {
assertEquals(StringUtils.nullToEmptyString(null), "");
assertEquals(StringUtils.nullToEmptyString("foo"), "foo");
}
@Test
public void testTextToHtml() {
assertEquals(StringUtils.textToHtml("line1\nline2"), "line1<br>line2");
assertEquals(StringUtils.textToHtml("line1\n\nline2"), "line1<p>line2");
}
}