CCM NG: started to replace oro.text.regex with java.util.regex, added some tests

git-svn-id: https://svn.libreccm.org/ccm/ccm_ng@3529 8810af33-2d31-482b-a856-94f89814c4df
pull/2/head
konermann 2015-07-23 09:43:25 +00:00
parent 1071d2466b
commit 91cb6dddb0
3 changed files with 445 additions and 356 deletions

View File

@ -249,7 +249,7 @@ public class Assert {
final String label) { final String label) {
if (object == null) { if (object == null) {
final String message = final String message =
label != null && label.trim().length() > 0 label != null && !label.isEmpty()
? "Value of " + label + " is null." ? "Value of " + label + " is null."
: DEFAULT_MESSAGE ; : DEFAULT_MESSAGE ;

View File

@ -25,12 +25,13 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.StringTokenizer; import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.oro.text.perl.Perl5Util; import org.apache.oro.text.perl.Perl5Util;
import org.apache.oro.text.regex.MalformedPatternException; import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult; import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern; //import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.PatternMatcherInput; import org.apache.oro.text.regex.PatternMatcherInput;
import org.apache.oro.text.regex.Perl5Compiler; import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher; import org.apache.oro.text.regex.Perl5Matcher;
@ -140,7 +141,7 @@ public class StringUtils {
// first take out new-lines // first take out new-lines
s = s.replaceAll("\n", ""); s = s.replaceAll("\n", "");
s = s.replaceAll("\r", ""); s = s.replaceAll("\r", "");
s = s.replaceAll("<[pP]>", "\n\n"); s = s.replaceAll("<[pP]>", "\n\n");
s = s.replaceAll("<br>", "\n"); s = s.replaceAll("<br>", "\n");
// take out other tags // take out other tags
@ -192,19 +193,33 @@ public class StringUtils {
*/ */
public static String smartTextToHtml(String s) { public static String smartTextToHtml(String s) {
ArrayList blocks = new ArrayList(); ArrayList blocks = new ArrayList();
//first splits the string at every new line
s_re.split(blocks, "/\\r?\\n(\\r?\\n)+/", s); s_re.split(blocks, "/\\r?\\n(\\r?\\n)+/", s);
// String[] blocks = s.split("[\n\r]");
Pattern hrpattern = Pattern.compile("-{3,}|_{3,}");
Pattern asterisk = Pattern.compile("^\\*");
Pattern plus = Pattern.compile("^\\+");
Pattern word = Pattern.compile(".*[a-zA-Z_0-9\\*\\+].*"); // \\w
StringBuffer html = new StringBuffer(""); StringBuffer html = new StringBuffer("");
Iterator i = blocks.iterator(); Iterator i = blocks.iterator();
while (i.hasNext()) { while (i.hasNext()) {
String block = (String) i.next(); String block = (String) i.next();
if (s_re.match("/^\\s*(___+|---+)\\s*$/", block)) {
Matcher hrmatcher = hrpattern.matcher(block);
Matcher asteriskmatcher = asterisk.matcher(block);
Matcher plusmatcher = plus.matcher(block);
Matcher wordmatcher = word.matcher(block);
if (hrmatcher.find()) { // horizontal line
html.append("<hr/>"); html.append("<hr/>");
} else if (s_re.match("/^\\*\\s/", block)) { } else if (asteriskmatcher.find()) {
html.append(smartTextList("/^\\*\\s+/m", "ul", block)); html.append(smartTextList("(?m)^\\*+\\s", "ul", block)); //bulleted list
} else if (s_re.match("/^\\+\\s/", block)) { } else if (plusmatcher.find()) {
html.append(smartTextList("/^\\+\\s+/m", "ol", block)); html.append(smartTextList("(?m)^\\++\\s", "ol", block)); //numerated list
} else if (s_re.match("/\\w/", block)) { } else if (wordmatcher.find()) {
html.append("<div>\n" + smartTextInline(block) + "\n</div>"); html.append("<div>\n" + smartTextInline(block) + "\n</div>");
} }
html.append("\n"); html.append("\n");
@ -212,45 +227,55 @@ public class StringUtils {
return html.toString(); return html.toString();
} }
/**
*
* @param match
* @param type
* @param s
* @return
*/
private static String smartTextList(String match, private static String smartTextList(String match,
String type, String type,
String s) { String s) {
ArrayList blocks = new ArrayList(); // ArrayList blocks = new ArrayList();
s_re.split(blocks, match, s); // s_re.split(blocks, match, s);
String[] blocks = s.split(match);
StringBuffer list = new StringBuffer("<" + type + ">\n"); StringBuffer list = new StringBuffer("<" + type + ">\n");
Iterator i = blocks.iterator(); // Iterator i = blocks.iterator();
while (i.hasNext()) {
String block = (String) i.next();
for (int j = 0; j < blocks.length; j++) {
String block = blocks[j];
if ("".equals(block)) { if ("".equals(block)) {
continue; continue;
} }
list.append("<li>\n"); list.append("<li>\n");
list.append(smartTextInline(block)); list.append(smartTextInline(block));
list.append("</li>\n"); list.append("</li>\n");
} }
list.append("</" + type + ">"); list.append("</" + type + ">");
return list.toString(); return list.toString();
} }
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;");
s_entities.put("fraction14", "&frac14;"); // s_entities.put("fraction14", "&frac14;");
s_entities.put("fraction34", "&frac34;"); // s_entities.put("fraction34", "&frac34;");
s_entities.put("copyright", "&copy;"); // s_entities.put("copyright", "&copy;");
s_entities.put("registered", "&reg;"); // s_entities.put("registered", "&reg;");
s_entities.put("trademark", "<sup>TM</sup>"); // s_entities.put("trademark", "<sup>TM</sup>");
s_log.debug("Static initalizer finished."); // s_log.debug("Static initalizer finished.");
} // }
/**
* dont use directly, use smartTextToHtml instead
*
* @param s
* @return
*/
private static String smartTextInline(String s) { private static String smartTextInline(String s) {
HashMap links = new HashMap();
if (s_log.isDebugEnabled()) { if (s_log.isDebugEnabled()) {
s_log.debug("Input {" + s + "}"); s_log.debug("Input {" + s + "}");
} }
@ -258,90 +283,70 @@ public class StringUtils {
// We're going to use the octal characters \u0001 and \u0002 for // We're going to use the octal characters \u0001 and \u0002 for
// escaping stuff, so we'd better make sure there aren't any // escaping stuff, so we'd better make sure there aren't any
// in the text. // in the text.
s = s_re.substitute("s/\u0001|\u0002|\u0003//g", s); s = s.replaceAll("[\u0001|\u0002|\u0003]", "");
// We transform a few common symbols // We transform a few common symbols
// We don't substitute them straight in because the s = s.replaceAll("1/4", "&frac14;");
// substituted text might interfere with stuff that s = s.replaceAll("1/2", "&frac12;");
// follows... s = s.replaceAll("3/4", "&frac34;");
s = s_re.substitute("s|\\b1/4\\b|\u0003fraction14\u0003|gx", s); s = s.replaceAll("\\([Cc]\\)", "&copy;");
s = s_re.substitute("s|\\b1/2\\b|\u0003fraction12\u0003|gx", s); s = s.replaceAll("\\([Rr]\\)", "&reg;");
s = s_re.substitute("s|\\b3/4\\b|\u0003fraction34\u0003|gx", s); s = s.replaceAll("\\(TM\\)|\\(tm\\)", "<sup>TM</sup>");
s = s_re.substitute("s|\\(C\\)|\u0003copyright\u0003|gx", s); s = s.replaceAll("^\\+", "");
s = s_re.substitute("s|\\(R\\)|\u0003registered\u0003|gx", s);
s = s_re.substitute("s|\\(TM\\)|\u0003trademark\u0003|gx", s);
if (s_log.isDebugEnabled()) { if (s_log.isDebugEnabled()) {
s_log.debug("After entities {" + s + "}"); s_log.debug("After entities {" + s + "}");
} }
// We've got to protect the url of titled links before we go further,
// however we can't actually generate the link yet because
// that interferes with the monospace stuff below....
s = s_re.substitute("s|@@|\u0001|gx", s);
s = smartTextReplace(new TitledLinkSubstitution(links),
"@([^\\(@]+)\\(([^\\)]+)\\)", s);
// We protect hyperlinks so that the '/' or '@' doesn't get
// mistaken for a block of italics / link
s = smartTextReplace(new UntitledLinkSubstitution(links),
"([a-z]+:\\/\\/[^\\s,\\(\\)><]*)", s);
s = smartTextReplace(new UntitledLinkSubstitution(links),
"(mailto:[^\\s,\\(\\)><]*)", s);
if (s_log.isDebugEnabled()) {
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> s = s.replaceAll("/+([a-zA-Z_0-9]+)+/", "<em>$1</em>");
// interfere with the pattern matching
s = s_re.substitute("s|//|\u0001|gx", s);
//s = s_re.substitute("s|(?<!\\w)/([^/]+)/(?!\\w)|<em>$1</em>|gx", s);
s = s_re.substitute("s|(\\W)/([^/]+)/(?!\\w)|$1<em>$2</em>|gx", s);
s = s_re.substitute("s|\u0001|/|gx", s);
// Lets process bold text *bold* // Lets process bold text *bold*
s = s_re.substitute("s|\\*\\*|\u0001|gx", s); s = s.replaceAll("\\*+([a-zA-Z_0-9]+)+\\*", "<strong>$1</strong>");
//s = s_re.substitute("s|(?<!\\w)\\*([^\\*]+)\\*(?!\\w)|<strong>$1</strong>|gx", s);
s = s_re.substitute("s|(\\W)\\*([^\\*]+)\\*(?!\\w)|$1<strong>$2</strong>|gx", s);
s = s_re.substitute("s|\u0001|*|gx", s);
// Now we're onto the monospace stuff =monospace= // Now we're onto the monospace stuff =monospace=
s = s_re.substitute("s|==|\u0001|gx", s); s = s.replaceAll("\\=+([a-zA-Z_0-9]+)+\\=", "<code>$1</code>");
//s = s_re.substitute("s|(?<!\\w)=([^=]+)=(?!\\w)|<code>$1</code>|gx", s);
s = s_re.substitute("s|(\\W)=([^=]+)=(?!\\w)|$1<code>$2</code>|gx", s);
s = s_re.substitute("s|\u0001|=|gx", s);
if (s_log.isDebugEnabled()) { if (s_log.isDebugEnabled()) {
s_log.debug("After styles {" + s + "}"); s_log.debug("After styles {" + s + "}");
} }
// Links are next on the list @text(url) // untitled mailto
s = s_re.substitute("s|@@|\u0001|gx", s); //"mailto:dan@berrange.com" to
s = s_re.substitute("s|@([^\\(@]+)\\(([^\\)]+)\\)|<a href=\"$2\">$1</a>|gx", s); //"<a href=\"mailto:dan@berrange.com\">mailto:dan@berrange.com</a>"
s = s_re.substitute("s|\u0001|@|gx", s); s = s.replaceAll("mailto:([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})\\b",
if (s_log.isDebugEnabled()) { "<a href=\\\"mailto:$1\\\">mailto:$1</a>");
s_log.debug("After links pass two {" + s + "}");
}
// Finally we can unobscure the hyperlinks //adding a '@' before every untitled link so it does not interfere with
s = smartTextReplace(new UnobscureSubstitution(links), // titled links
"\u0002([^\u0002]+)\u0002", s); s = s.replaceAll("(http[s]*://www\\..+\\.[A-Za-z]{2,4})",
s = s_re.substitute("s|\u0001|@|gx", s); "@$1");
if (s_log.isDebugEnabled()) {
s_log.debug("After links pass three {" + s + "}"); // titled Links
} //"@google(http://www.google.com) to
//<a href=\"http://www.google.com\">google</a>"
s = s.replaceAll("@(\\w+)\\(@(http*[s]*:*/*/*www\\..+\\.[A-Za-z]{2,4})\\)",
"<a href=\\\"$2\\\">$1</a>");
//titled mailto
//"@Dan B(mailto:dan@@berrange.com)" to
//"<a href=\"mailto:dan@berrange.com\">Dan B</a>"
s = s.replaceAll("@([\\w\\s]+)\\(mailto:([a-zA-Z0-9._%+-]+@@[a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})\\)",
"<a href=\\\"mailto:$2\\\">$1</a>");
//remove one of the two @'s
s = s.replaceAll("mailto:([a-zA-Z0-9._%+-]+)+@@([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})",
"mailto:$1@$2");
//untitled links (which got an '@' in front now)
s = s.replaceAll("@(http[s]*://www\\..+\\.[A-Za-z]{2,4})",
"<a href=\\\"$1\\\">$1</a>");
// And those entities
s = smartTextReplace(new EntitySubstitution(),
"\u0003([^\u0003]+)\u0003", s);
if (s_log.isDebugEnabled()) { if (s_log.isDebugEnabled()) {
s_log.debug("After entities (complete) {" + s + "}"); s_log.debug("After links {" + s + "}");
} }
return s; return s;
} }
/** /**
* same as replaceAll()?
* *
* @param subst * @param subst
* @param pattern * @param pattern
@ -367,122 +372,120 @@ public class StringUtils {
throw new UncheckedWrapperException("cannot perform substitution", e); throw new UncheckedWrapperException("cannot perform substitution", e);
} }
return result.toString(); return result.toString();
} }
/** /**
* *
*/ */
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) {
m_hash = hash; // m_hash = hash;
} // }
//
@Override // @Override
public void appendSubstitution(StringBuffer appendBuffer, // public void appendSubstitution(StringBuffer appendBuffer,
MatchResult match, // MatchResult match,
int substitutionCount, // int substitutionCount,
PatternMatcherInput originalInput, // PatternMatcherInput originalInput,
PatternMatcher matcher, // PatternMatcher matcher,
Pattern pattern) { // Pattern pattern) {
String title = match.group(1); // String title = match.group(1);
String link = match.group(2); // String link = match.group(2);
s_log.debug("Link: " + link); // s_log.debug("Link: " + link);
//
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 = "@" + title + "(\u0002" + i.toString() + "\u0002)"; // String dst = "@" + title + "(\u0002" + i.toString() + "\u0002)";
appendBuffer.append(dst); // appendBuffer.append(dst);
s_log.debug("Encoded Link: " + dst); // s_log.debug("Encoded Link: " + dst);
} // }
} // }
// /**
/** // *
* // */
*/ // private static class UnobscureSubstitution implements Substitution {
private static class UntitledLinkSubstitution implements Substitution { //
// private Map m_hash;
private Map m_hash; //
// public UnobscureSubstitution(Map hash) {
public UntitledLinkSubstitution(Map hash) { // m_hash = hash;
m_hash = hash; // }
} //
// public void appendSubstitution(StringBuffer appendBuffer,
public void appendSubstitution(StringBuffer appendBuffer, // MatchResult match,
MatchResult match, // int substitutionCount,
int substitutionCount, // PatternMatcherInput originalInput,
PatternMatcherInput originalInput, // PatternMatcher matcher,
PatternMatcher matcher, // Pattern pattern) {
Pattern pattern) { // String s = match.group(1);
String link = match.group(1); // s_log.debug("Key: " + s);
s_log.debug("Link: " + link); //
// Integer i = Integer.valueOf(s);
Integer i = m_hash.size(); // appendBuffer.append((String) m_hash.get(i));
s_log.debug("Key: " + i); // s_log.debug("Link: " + m_hash.get(i));
m_hash.put(i, link); // }
String dst = "@\u0002" + i.toString() + "\u0002(\u0002" // }
+ i.toString() + "\u0002)"; //
appendBuffer.append(dst); // /**
s_log.debug("Encoded Link: " + dst); // *
} // */
} // private static class EntitySubstitution implements Substitution {
//
/** // public void appendSubstitution(StringBuffer appendBuffer,
* // MatchResult match,
*/ // int substitutionCount,
private static class UnobscureSubstitution implements Substitution { // PatternMatcherInput originalInput,
// PatternMatcher matcher,
private Map m_hash; // Pattern pattern) {
// String s = match.group(1);
public UnobscureSubstitution(Map hash) { // s_log.debug("Key: " + s);
m_hash = hash; //
} // appendBuffer.append((String) s_entities.get(s));
// s_log.debug("Entity: " + s_entities.get(s));
public void appendSubstitution(StringBuffer appendBuffer, // }
MatchResult match, // }
int substitutionCount, //
PatternMatcherInput originalInput, // private Map m_hash;
PatternMatcher matcher, //
Pattern pattern) { // public UntitledLinkSubstitution(Map hash) {
String s = match.group(1); // m_hash = hash;
s_log.debug("Key: " + s); // }
//
Integer i = Integer.valueOf(s); // public void appendSubstitution(StringBuffer appendBuffer,
appendBuffer.append((String) m_hash.get(i)); // MatchResult match,
s_log.debug("Link: " + m_hash.get(i)); // int substitutionCount,
} // PatternMatcherInput originalInput,
} // PatternMatcher matcher,
// Pattern pattern) {
/** // String link = match.group(1);
* // s_log.debug("Link: " + link);
*/ //
private static class EntitySubstitution implements Substitution { // Integer i = m_hash.size();
// s_log.debug("Key: " + i);
public void appendSubstitution(StringBuffer appendBuffer, // m_hash.put(i, link);
MatchResult match, // String dst = "@\u0002" + i.toString() + "\u0002(\u0002"
int substitutionCount, // + i.toString() + "\u0002)";
PatternMatcherInput originalInput, // appendBuffer.append(dst);
PatternMatcher matcher, // s_log.debug("Encoded Link: " + dst);
Pattern pattern) { // }
String s = match.group(1); // }
s_log.debug("Key: " + s);
appendBuffer.append((String) s_entities.get(s));
s_log.debug("Entity: " + s_entities.get(s));
}
}
/** /**
* Convert a string of items separated by a separator character to an * Convert a string of items separated by a separator character to an
* (string)array of the items. sep is the separator character. Example: * (string)array of the items. sep is the separator character. Example:
* Input - s == "cat,house,dog" sep==',' Output - {"cat", "house", "dog"} * Input - s == "cat,house,dog,," sep==',' Output - {"cat", "house", "dog",
* "" ,""} different to java.lang.String.split(): Input - s ==
* "cat,house,dog,," sep==',' 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.
*
*/ */
public static String[] split(String s, char sep) { public static String[] split(String s, char sep) {
ArrayList al = new ArrayList(); ArrayList al = new ArrayList();
@ -564,7 +567,7 @@ public class StringUtils {
* 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();
@ -782,15 +785,8 @@ public class StringUtils {
* @post result.indexOf('\n') == 0 * @post result.indexOf('\n') == 0
*/ */
public static String stripNewLines(String str) { public static String stripNewLines(String str) {
int len = str.length();
StringBuffer sb = new StringBuffer(len); return str.replaceAll("[\\n\\r]", "");
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch != '\r' && ch != '\n') {
sb.append(ch);
}
}
return sb.toString();
} }
/** /**
@ -1069,28 +1065,27 @@ public class StringUtils {
* @see java.text.MessageFormat * @see java.text.MessageFormat
* *
* @param text the text to interpolate * @param text the text to interpolate
* @param vars a hash table containing key -> value mappings * @param vars a hash table containing key -> value mappings ////
*/ */
public static String interpolate(String text, Map vars) { // public static String interpolate(String text, Map vars) {
HashSubstitution subst = new HashSubstitution(vars); // HashSubstitution subst = new HashSubstitution(vars);
Perl5Matcher matcher = new Perl5Matcher(); // Perl5Matcher matcher = new Perl5Matcher();
Perl5Compiler compiler = new Perl5Compiler(); // Perl5Compiler compiler = new Perl5Compiler();
StringBuffer result = new StringBuffer(); // StringBuffer result = new StringBuffer();
PatternMatcherInput input = new PatternMatcherInput(text); // PatternMatcherInput input = new PatternMatcherInput(text);
//
try { // try {
Util.substitute(result, // Util.substitute(result,
matcher, // matcher,
compiler.compile("(::(?:\\w+(?:[.-]+\\w+)*)::)"), // compiler.compile("(::(?:\\w+(?:[.-]+\\w+)*)::)"),
subst, // subst,
input, // input,
Util.SUBSTITUTE_ALL); // Util.SUBSTITUTE_ALL);
} catch (MalformedPatternException e) { // } catch (MalformedPatternException e) {
throw new UncheckedWrapperException("cannot perform substitution", e); // throw new UncheckedWrapperException("cannot perform substitution", e);
} // }
return result.toString(); // return result.toString();
} // }
/** /**
* THis method performs a single variable substitution on a string. The * THis method performs a single variable substitution on a string. The
* placeholder takes the form of ::key:: within the sample text. * placeholder takes the form of ::key:: within the sample text.
@ -1117,44 +1112,10 @@ public class StringUtils {
public static String replace(final String str, public static String replace(final String str,
final String find, final String find,
final String replace) { final String replace) {
Assert.exists(find, String.class);
Assert.exists(replace, String.class);
if (str == null) { if (str == null) {
return null; return null;
} }
return str.replace(find, replace);
int cur = str.indexOf(find);
if (cur < 0) {
return str;
}
final int findLength = find.length();
// If replace is longer than find, assume the result is going to be
// slightly longer than the original string.
final int bufferLength
= replace.length() > findLength ? (int) (str.length() * 1.1) : str.length();
StringBuffer sb = new StringBuffer(bufferLength);
int last = 0;
if (cur == 0) {
sb.append(replace);
cur = str.indexOf(find, cur + findLength);
last = findLength;
}
while (cur > 0) {
sb.append(str.substring(last, cur));
sb.append(replace);
last = cur + findLength;
cur = str.indexOf(find, cur + findLength);
}
if (last < str.length() - 1) {
sb.append(str.substring(last));
}
return sb.toString();
} }
/** /**
@ -1174,69 +1135,68 @@ public class StringUtils {
/** /**
* *
*/ */
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) {
m_hash = hash; // m_hash = hash;
} // }
//
public void appendSubstitution(StringBuffer appendBuffer, // public void appendSubstitution(StringBuffer appendBuffer,
MatchResult match, // MatchResult match,
int substitutionCount, // int substitutionCount,
PatternMatcherInput originalInput, // PatternMatcherInput originalInput,
PatternMatcher matcher, // PatternMatcher matcher,
Pattern pattern) { // Pattern pattern) {
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);
//
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());
} // }
} // }
//
value = (m_hash.containsKey(key) ? m_hash.get(key) : ""); // value = (m_hash.containsKey(key) ? m_hash.get(key) : "");
//
String val; // String val;
if (value instanceof PlaceholderValueGenerator) { // if (value instanceof PlaceholderValueGenerator) {
PlaceholderValueGenerator gen = (PlaceholderValueGenerator) value; // PlaceholderValueGenerator gen = (PlaceholderValueGenerator) value;
val = gen.generate(key); // val = gen.generate(key);
} else if (value.getClass().isArray()) { // } else if (value.getClass().isArray()) {
Object[] values = (Object[]) value; // Object[] values = (Object[]) value;
//
StringBuffer buf = new StringBuffer(); // StringBuffer buf = new StringBuffer();
for (int i = 0; i < values.length; i++) { // for (int i = 0; i < values.length; i++) {
buf.append(values[i].toString()); // buf.append(values[i].toString());
if ((values.length - 1) != i) { // if ((values.length - 1) != i) {
buf.append(", "); // buf.append(", ");
} // }
} // }
//
val = buf.toString(); // val = buf.toString();
} else { // } else {
val = value.toString(); // val = value.toString();
} // }
//
appendBuffer.append(val); // appendBuffer.append(val);
} // }
} // }
/** /**
* @throws NullPointerException if <code>throwable</code> is null * @throws NullPointerException if <code>throwable</code> is null
*/ */

View File

@ -142,7 +142,105 @@ public class StringUtilsTest {
+ "</div>\n"; + "</div>\n";
String actual = StringUtils.smartTextToHtml(src); String actual = StringUtils.smartTextToHtml(src);
assertTrue(expected.equals(actual)); // assertTrue(expected.equals(actual));
String errMsg = "smartTexttoHtml, expected = " + expected
+ " found = " + actual;
assertEquals(errMsg, expected, actual);
}
@Test
public void testSmartTextHR() {
String src = "---";
String expected = "<hr/>\n";
String actual = StringUtils.smartTextToHtml(src);
String errMsg = "smartTexttoHtml, expected = " + expected
+ " found = " + actual;
assertEquals(errMsg, expected, actual);
}
@Test
public void testSmartTextURL() {
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 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 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);
String errMsg = "smartTexttoHtml, expected = " + expected
+ " found = " + actual;
assertEquals(errMsg, expected, actual);
}
@Test
public void testSmartTextLists() {
String src = "+ now an enumerated list item\n"
+ "+ and one /more/\n"
+ "+ this one is split over two lines\n"
+ "for testing purposes\n";
String expected = "<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\n"
+ "</li>\n"
+ "</ol>\n";
String actual = StringUtils.smartTextToHtml(src);
String errMsg = "smartTexttoHtml, expected = " + expected
+ " found = " + actual;
assertEquals(errMsg, expected, actual);
}
@Test
public void testSmartTextLists2() {
String src = "* a bullet list\n"
+ "* more *bullets* in\n"
+ " this list element\n"
+ "* a final element\n";
String expected = "<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\n"
+ "</li>\n"
+ "</ul>\n";
String actual = StringUtils.smartTextToHtml(src);
String errMsg = "smartTexttoHtml, expected = " + expected
+ " found = " + actual;
assertEquals(errMsg, expected, actual);
} }
@Test @Test
@ -227,6 +325,34 @@ public class StringUtilsTest {
assertEquals(errMsg, expected, found); assertEquals(errMsg, expected, found);
} }
@Test
public void testSplitUp() {
String s = "/packages/foo/xsl/::vhost::/foo_::locale::.xsl";
List list = new ArrayList();
list = StringUtils.splitUp(s, "/::\\w+::/");
// if you want to see the result:
// assertEquals("splitup:"
// +(String)list.get(0)+", " +
// (String)list.get(1)+", " +
// (String)list.get(2)+", "
//// + (String)list.get(3)+", "
//// +(String)list.get(4)+", "
// +"sizekram="
// + list.size(), list.size(), 99);
verifySplit("/packages/foo/xsl/", (String)list.get(0));
verifySplit("::vhost::", (String)list.get(1));
verifySplit("/foo_", (String)list.get(2));
verifySplit("::locale::", (String)list.get(3));
verifySplit(".xsl",(String)list.get(4));
assertEquals("expected array length 5, found="
+ list.size(), list.size(), 5);
}
@Test @Test
public void testJoinChar() { public void testJoinChar() {
@ -248,7 +374,6 @@ public class StringUtilsTest {
String errMsg = "join string, expected = " + expected String errMsg = "join string, expected = " + expected
+ " found = " + found; + " found = " + found;
assertEquals(errMsg, expected, found); assertEquals(errMsg, expected, found);
} }
@Test @Test
@ -294,21 +419,19 @@ public class StringUtilsTest {
String in = "<p>this is the text<br>newline .</p>one<br><b>two</b><br>"; 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 expected_out = "\n\nthis is the text\nnewline . one\n two \n";
String actual_out = StringUtils.htmlToText(in); String actual_out = StringUtils.htmlToText(in);
String errMsg = "htmlToText, expected = " + expected_out String errMsg = "htmlToText, expected = " + expected_out
+ " found = " + actual_out; + " found = " + actual_out;
assertEquals(errMsg, expected_out, actual_out); assertEquals(errMsg, expected_out, actual_out);
in = "Text with <a <b <c > strange markup"; in = "Text with <a <b <c > strange markup";
expected_out = "Text with strange markup"; expected_out = "Text with strange markup";
actual_out = StringUtils.htmlToText(in); actual_out = StringUtils.htmlToText(in);
errMsg = "htmlToText, expected = " + expected_out errMsg = "htmlToText, expected = " + expected_out
+ " found = " + actual_out; + " found = " + actual_out;
assertEquals(errMsg,expected_out, actual_out); assertEquals(errMsg, expected_out, actual_out);
} }
@Test @Test
@ -387,29 +510,28 @@ public class StringUtilsTest {
actual_out); actual_out);
} }
@Test //// @Test
public void testPlaceholders() { //// public void testPlaceholders() {
String in = "foo ::bar:: wizz"; //// String in = "foo ::bar:: wizz";
String expected_out = "foo eek wizz"; //// String expected_out = "foo eek wizz";
String actual_out = StringUtils.interpolate(in, "bar", "eek"); //// String actual_out = StringUtils.interpolate(in, "bar", "eek");
////
assertEquals("interpolate failed simple placeholder", //// assertEquals("interpolate failed simple placeholder",
expected_out, //// expected_out,
actual_out); //// actual_out);
////
HashMap vars = new HashMap(); //// HashMap vars = new HashMap();
vars.put("bar", "eek"); //// vars.put("bar", "eek");
vars.put("more", "wibble"); //// vars.put("more", "wibble");
////
in = "foo ::bar:: wizz ::more:: done"; //// in = "foo ::bar:: wizz ::more:: done";
expected_out = "foo eek wizz wibble done"; //// expected_out = "foo eek wizz wibble done";
actual_out = StringUtils.interpolate(in, vars); //// actual_out = StringUtils.interpolate(in, vars);
assertEquals("interpolate failed hashmap test", //// assertEquals("interpolate failed hashmap test",
expected_out, //// expected_out,
actual_out); //// actual_out);
////
} //// }
@Test @Test
public void testReplace() { public void testReplace() {
String[] pairs = {null, null, String[] pairs = {null, null,
@ -434,6 +556,13 @@ public class StringUtilsTest {
assertEquals(expected, actual); assertEquals(expected, actual);
} }
} }
// @Test
// public void testSmartTextReplace(){
// String src = "this is the original text";
// String expected = "this is the expected text";
// String actual = StringUtils.smartTextReplace("original","original",src);
// }
@Test @Test
public void testUrlize() { public void testUrlize() {