一、前言
关于htmlunit源码包中的com.gargoylesoftware.htmlunit.util.StringUtils字符串工具类,进行过滤xml字符串escapeXmlChars、判断是否包含空格containsWhitespace、字符串转日期parseHttpDate、RGB颜色字符串判断isColorRGB,格式化颜色转字符串标记formatColor等处理。
二、源码说明
1.StringUtils类
package com.gargoylesoftware.htmlunit.util;@b@@b@import com.gargoylesoftware.htmlunit.WebAssert;@b@import java.awt.Color;@b@import java.util.Collection;@b@import java.util.Date;@b@import java.util.regex.Matcher;@b@import java.util.regex.Pattern;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@import org.apache.http.impl.cookie.DateParseException;@b@import org.apache.http.impl.cookie.DateUtils;@b@@b@public final class StringUtils@b@{@b@ private static final Pattern HEX_COLOR = Pattern.compile("#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})");@b@ private static final Pattern RGB_COLOR = Pattern.compile("rgb\\s*?\\(\\s*?(\\d{1,3})\\s*?,\\s*?(\\d{1,3})\\s*?,\\s*?(\\d{1,3})\\s*?\\)");@b@ private static final Log LOG = LogFactory.getLog(StringUtils.class);@b@@b@ public static String escapeXmlChars(String s)@b@ {@b@ return org.apache.commons.lang.StringUtils.replaceEach(s, new String[] { "&", "<", ">" }, new String[] { "&", "<", ">" });@b@ }@b@@b@ public static String escapeXmlAttributeValue(String attValue)@b@ {@b@ int len = attValue.length();@b@ StringBuilder sb = null;@b@ for (int i = len - 1; i >= 0; --i) {@b@ char c = attValue.charAt(i);@b@ String replacement = null;@b@ if (c == '<') {@b@ replacement = "<";@b@ }@b@ else if (c == '&') {@b@ replacement = "&";@b@ }@b@ else if (c == '"') {@b@ replacement = """;@b@ }@b@@b@ if (replacement != null) {@b@ if (sb == null)@b@ sb = new StringBuilder(attValue);@b@@b@ sb.replace(i, i + 1, replacement);@b@ }@b@ }@b@@b@ if (sb != null)@b@ return sb.toString();@b@@b@ return attValue;@b@ }@b@@b@ public static boolean containsWhitespace(String s)@b@ {@b@ char[] arr$ = s.toCharArray(); int len$ = arr$.length; for (int i$ = 0; i$ < len$; ++i$) { char c = arr$[i$];@b@ if (Character.isWhitespace(c))@b@ return true;@b@ }@b@@b@ return false;@b@ }@b@@b@ public static int indexOf(String s, char searchChar, int beginIndex, int endIndex)@b@ {@b@ for (int i = beginIndex; i < endIndex; ++i)@b@ if (s.charAt(i) == searchChar)@b@ return i;@b@@b@@b@ return -1;@b@ }@b@@b@ public static boolean isFloat(String s, boolean trim)@b@ {@b@ boolean ok;@b@ if (trim) {@b@ s = s.trim();@b@ }@b@@b@ try@b@ {@b@ Float.parseFloat(s);@b@ ok = true;@b@ }@b@ catch (NumberFormatException e) {@b@ ok = false;@b@ }@b@@b@ return ok;@b@ }@b@@b@ public static boolean containsCaseInsensitive(Collection<String> strings, String string)@b@ {@b@ string = string.toLowerCase();@b@ for (String s : strings)@b@ if (s.equalsIgnoreCase(string))@b@ return true;@b@@b@@b@ return false;@b@ }@b@@b@ public static Date parseHttpDate(String s)@b@ {@b@ if (s == null)@b@ return null;@b@ try@b@ {@b@ return DateUtils.parseDate(s);@b@ }@b@ catch (DateParseException e) {@b@ LOG.warn("Unable to parse http date: '" + s + "'"); }@b@ return null;@b@ }@b@@b@ public static boolean isColorHexadecimal(String token)@b@ {@b@ if (token == null)@b@ return false;@b@@b@ return HEX_COLOR.matcher(token.trim()).matches();@b@ }@b@@b@ public static Color asColorHexadecimal(String token)@b@ {@b@ if (token == null)@b@ return null;@b@@b@ Matcher tmpMatcher = HEX_COLOR.matcher(token);@b@ boolean tmpFound = tmpMatcher.matches();@b@ if (!(tmpFound)) {@b@ return null;@b@ }@b@@b@ String tmpHex = tmpMatcher.group(1);@b@ if (tmpHex.length() == 6) {@b@ tmpRed = Integer.parseInt(tmpHex.substring(0, 2), 16);@b@ tmpGreen = Integer.parseInt(tmpHex.substring(2, 4), 16);@b@ tmpBlue = Integer.parseInt(tmpHex.substring(4, 6), 16);@b@ tmpColor = new Color(tmpRed, tmpGreen, tmpBlue);@b@ return tmpColor;@b@ }@b@@b@ int tmpRed = Integer.parseInt(tmpHex.substring(0, 1) + tmpHex.substring(0, 1), 16);@b@ int tmpGreen = Integer.parseInt(tmpHex.substring(1, 2) + tmpHex.substring(1, 2), 16);@b@ int tmpBlue = Integer.parseInt(tmpHex.substring(2, 3) + tmpHex.substring(2, 3), 16);@b@ Color tmpColor = new Color(tmpRed, tmpGreen, tmpBlue);@b@ return tmpColor;@b@ }@b@@b@ public static boolean isColorRGB(String token)@b@ {@b@ if (token == null)@b@ return false;@b@@b@ return RGB_COLOR.matcher(token.trim()).matches();@b@ }@b@@b@ public static Color asColorRGB(String token)@b@ {@b@ if (token == null)@b@ return null;@b@@b@ Matcher tmpMatcher = RGB_COLOR.matcher(token);@b@ boolean tmpFound = tmpMatcher.matches();@b@ if (!(tmpFound)) {@b@ return null;@b@ }@b@@b@ int tmpRed = Integer.parseInt(tmpMatcher.group(1));@b@ int tmpGreen = Integer.parseInt(tmpMatcher.group(2));@b@ int tmpBlue = Integer.parseInt(tmpMatcher.group(3));@b@ Color tmpColor = new Color(tmpRed, tmpGreen, tmpBlue);@b@ return tmpColor;@b@ }@b@@b@ public static Color findColorRGB(String token)@b@ {@b@ if (token == null)@b@ return null;@b@@b@ Matcher tmpMatcher = RGB_COLOR.matcher(token);@b@ boolean tmpFound = tmpMatcher.find();@b@ if (!(tmpFound)) {@b@ return null;@b@ }@b@@b@ int tmpRed = Integer.parseInt(tmpMatcher.group(1));@b@ int tmpGreen = Integer.parseInt(tmpMatcher.group(2));@b@ int tmpBlue = Integer.parseInt(tmpMatcher.group(3));@b@ Color tmpColor = new Color(tmpRed, tmpGreen, tmpBlue);@b@ return tmpColor;@b@ }@b@@b@ public static String formatColor(Color aColor)@b@ {@b@ return "rgb(" + aColor.getRed() + ", " + aColor.getGreen() + ", " + aColor.getBlue() + ")";@b@ }@b@@b@ public static String formatHttpDate(Date date)@b@ {@b@ WebAssert.notNull("date", date);@b@ return DateUtils.formatDate(date);@b@ }@b@}
2.WebAssert类
package com.gargoylesoftware.htmlunit;@b@@b@import com.gargoylesoftware.htmlunit.html.HtmlAnchor;@b@import com.gargoylesoftware.htmlunit.html.HtmlElement;@b@import com.gargoylesoftware.htmlunit.html.HtmlInput;@b@import com.gargoylesoftware.htmlunit.html.HtmlPage;@b@import java.util.ArrayList;@b@import java.util.Arrays;@b@import java.util.List;@b@@b@public final class WebAssert@b@{@b@ public static void assertTitleEquals(HtmlPage page, String title)@b@ {@b@ String s = page.getTitleText();@b@ if (!(s.equals(title))) {@b@ String msg = "Actual page title '" + s + "' does not match expected page title '" + title + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTitleContains(HtmlPage page, String titlePortion)@b@ {@b@ String s = page.getTitleText();@b@ if (s.indexOf(titlePortion) == -1) {@b@ String msg = "Page title '" + s + "' does not contain the substring '" + titlePortion + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTitleMatches(HtmlPage page, String regex)@b@ {@b@ String s = page.getTitleText();@b@ if (!(s.matches(regex))) {@b@ String msg = "Page title '" + s + "' does not match the regular expression '" + regex + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertElementPresent(HtmlPage page, String id)@b@ {@b@ try@b@ {@b@ page.getHtmlElementById(id);@b@ }@b@ catch (ElementNotFoundException e) {@b@ String msg = "The page does not contain an element with ID '" + id + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertElementPresentByXPath(HtmlPage page, String xpath)@b@ {@b@ List elements = page.getByXPath(xpath);@b@ if (elements.isEmpty()) {@b@ String msg = "The page does not contain any elements matching the XPath expression '" + xpath + "'.";@b@@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertElementNotPresent(HtmlPage page, String id)@b@ {@b@ try@b@ {@b@ page.getHtmlElementById(id);@b@ }@b@ catch (ElementNotFoundException e) {@b@ return;@b@ }@b@ String msg = "The page contains an element with ID '" + id + "'.";@b@ throw new AssertionError(msg);@b@ }@b@@b@ public static void assertElementNotPresentByXPath(HtmlPage page, String xpath)@b@ {@b@ List elements = page.getByXPath(xpath);@b@ if (!(elements.isEmpty())) {@b@ String msg = "The page does not contain any elements matching the XPath expression '" + xpath + "'.";@b@@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTextPresent(HtmlPage page, String text)@b@ {@b@ if (page.asText().indexOf(text) == -1) {@b@ String msg = "The page does not contain the text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTextPresentInElement(HtmlPage page, String text, String id)@b@ {@b@ HtmlElement element;@b@ String msg;@b@ try@b@ {@b@ element = page.getHtmlElementById(id);@b@ if (element.asText().indexOf(text) == -1) {@b@ msg = "The element with ID '" + id + "' does not contain the text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@ catch (ElementNotFoundException e) {@b@ msg = "Unable to verify that the element with ID '" + id + "' contains the text '" + text + "' because the specified element does not exist.";@b@@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTextNotPresent(HtmlPage page, String text)@b@ {@b@ if (page.asText().contains(text)) {@b@ String msg = "The page contains the text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertTextNotPresentInElement(HtmlPage page, String text, String id)@b@ {@b@ HtmlElement element;@b@ String msg;@b@ try@b@ {@b@ element = page.getHtmlElementById(id);@b@ if (element.asText().contains(text)) {@b@ msg = "The element with ID '" + id + "' contains the text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@ catch (ElementNotFoundException e) {@b@ msg = "Unable to verify that the element with ID '" + id + "' does not contain the text '" + text + "' because the specified element does not exist.";@b@@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertLinkPresent(HtmlPage page, String id)@b@ {@b@ try@b@ {@b@ page.getDocumentElement().getOneHtmlElementByAttribute("a", "id", id);@b@ }@b@ catch (ElementNotFoundException e) {@b@ String msg = "The page does not contain a link with ID '" + id + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertLinkNotPresent(HtmlPage page, String id)@b@ {@b@ try@b@ {@b@ page.getDocumentElement().getOneHtmlElementByAttribute("a", "id", id);@b@@b@ String msg = "The page contains a link with ID '" + id + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ catch (ElementNotFoundException e)@b@ {@b@ }@b@ }@b@@b@ public static void assertLinkPresentWithText(HtmlPage page, String text)@b@ {@b@ boolean found = false;@b@ for (HtmlAnchor a : page.getAnchors())@b@ if (a.asText().contains(text)) {@b@ found = true;@b@ break;@b@ }@b@@b@ if (!(found)) {@b@ String msg = "The page does not contain a link with text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertLinkNotPresentWithText(HtmlPage page, String text)@b@ {@b@ boolean found = false;@b@ for (HtmlAnchor a : page.getAnchors())@b@ if (a.asText().contains(text)) {@b@ found = true;@b@ break;@b@ }@b@@b@ if (found) {@b@ String msg = "The page contains a link with text '" + text + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertFormPresent(HtmlPage page, String name)@b@ {@b@ try@b@ {@b@ page.getFormByName(name);@b@ }@b@ catch (ElementNotFoundException e) {@b@ String msg = "The page does not contain a form named '" + name + "'.";@b@ throw new AssertionError(msg);@b@ }@b@ }@b@@b@ public static void assertFormNotPresent(HtmlPage page, String name)@b@ {@b@ try@b@ {@b@ page.getFormByName(name);@b@ }@b@ catch (ElementNotFoundException e) {@b@ return;@b@ }@b@ String msg = "The page contains a form named '" + name + "'.";@b@ throw new AssertionError(msg);@b@ }@b@@b@ public static void assertInputPresent(HtmlPage page, String name)@b@ {@b@ String xpath = "//input[@name='" + name + "']";@b@ List list = page.getByXPath(xpath);@b@ if (list.isEmpty())@b@ throw new AssertionError("Unable to find an input element named '" + name + "'.");@b@ }@b@@b@ public static void assertInputNotPresent(HtmlPage page, String name)@b@ {@b@ String xpath = "//input[@name='" + name + "']";@b@ List list = page.getByXPath(xpath);@b@ if (!(list.isEmpty()))@b@ throw new AssertionError("Unable to find an input element named '" + name + "'.");@b@ }@b@@b@ public static void assertInputContainsValue(HtmlPage page, String name, String value)@b@ {@b@ String xpath = "//input[@name='" + name + "']";@b@ List list = page.getByXPath(xpath);@b@ if (list.isEmpty())@b@ throw new AssertionError("Unable to find an input element named '" + name + "'.");@b@@b@ HtmlInput input = (HtmlInput)list.get(0);@b@ String s = input.getValueAttribute();@b@ if (!(s.equals(value)))@b@ throw new AssertionError("The input element named '" + name + "' contains the value '" + s + "', not the expected value '" + value + "'.");@b@ }@b@@b@ public static void assertInputDoesNotContainValue(HtmlPage page, String name, String value)@b@ {@b@ String xpath = "//input[@name='" + name + "']";@b@ List list = page.getByXPath(xpath);@b@ if (list.isEmpty())@b@ throw new AssertionError("Unable to find an input element named '" + name + "'.");@b@@b@ HtmlInput input = (HtmlInput)list.get(0);@b@ String s = input.getValueAttribute();@b@ if (s.equals(value))@b@ throw new AssertionError("The input element named '" + name + "' contains the value '" + s + "', not the expected value '" + value + "'.");@b@ }@b@@b@ public static void assertAllTabIndexAttributesSet(HtmlPage page)@b@ {@b@ List tags = Arrays.asList(new String[] { "a", "area", "button", "input", "object", "select", "textarea" });@b@@b@ for (HtmlElement element : page.getDocumentElement().getHtmlElementsByTagNames(tags)) {@b@ Short tabIndex = element.getTabIndex();@b@ if ((tabIndex == null) || (tabIndex == HtmlElement.TAB_INDEX_OUT_OF_BOUNDS)) {@b@ String s = element.getAttribute("tabindex");@b@ throw new AssertionError("Illegal value for tab index: '" + s + "'.");@b@ }@b@ }@b@ }@b@@b@ public static void assertAllAccessKeyAttributesUnique(HtmlPage page)@b@ {@b@ List list = new ArrayList();@b@ for (HtmlElement element : page.getHtmlElementDescendants()) {@b@ String key = element.getAttribute("accesskey");@b@ if ((key != null) && (key.length() != 0)) {@b@ if (list.contains(key))@b@ throw new AssertionError("The access key '" + key + "' is not unique.");@b@@b@ list.add(key);@b@ }@b@ }@b@ }@b@@b@ public static void assertAllIdAttributesUnique(HtmlPage page)@b@ {@b@ List list = new ArrayList();@b@ for (HtmlElement element : page.getHtmlElementDescendants()) {@b@ String id = element.getAttribute("id");@b@ if ((id != null) && (id.length() != 0)) {@b@ if (list.contains(id))@b@ throw new AssertionError("The element ID '" + id + "' is not unique.");@b@@b@ list.add(id);@b@ }@b@ }@b@ }@b@@b@ public static void notNull(String description, Object object)@b@ {@b@ if (object == null)@b@ throw new NullPointerException(description);@b@ }@b@}