01: // Copyright © 2004-2007 ASERT. Released under the Canoo Webtest license.
02: package com.canoo.webtest.boundary;
03:
04: import java.io.IOException;
05: import java.net.URL;
06:
07: import org.apache.log4j.Logger;
08: import org.jaxen.JaxenException;
09: import org.jaxen.XPath;
10:
11: import com.canoo.webtest.engine.StepExecutionException;
12: import com.canoo.webtest.engine.xpath.XPathHelper;
13: import com.canoo.webtest.steps.Step;
14: import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
15: import com.gargoylesoftware.htmlunit.Page;
16: import com.gargoylesoftware.htmlunit.WebClient;
17:
18: /**
19: * Boundary class for interacting with HtmlUnit.
20: *
21: * @author Paul King
22: * @author Marc Guillemot
23: */
24: public final class HtmlUnitBoundary {
25: private static final Logger LOG = Logger
26: .getLogger(HtmlUnitBoundary.class);
27:
28: private HtmlUnitBoundary() {
29: }
30:
31: public static Page tryGetPage(final URL url,
32: final WebClient webClient) {
33: return tryGetPage(url, webClient, true);
34: }
35:
36: public static Page tryGetPageNoFail(final URL url,
37: final WebClient webClient) {
38: return tryGetPage(url, webClient, false);
39: }
40:
41: private static Page tryGetPage(final URL url,
42: final WebClient webClient, final boolean shouldFail) {
43: try {
44: LOG
45: .debug("Visiting: " + url + " (fail=" + shouldFail
46: + ")");
47: return webClient.getPage(url);
48: } catch (final FailingHttpStatusCodeException e) {
49: LOG.debug("Testing " + url + " failed: status code "
50: + e.getStatusCode() + "(" + e.getStatusMessage()
51: + ")");
52: return returnNullOrFail(e, shouldFail);
53: } catch (final IOException e) {
54: LOG.debug("Testing " + url + " failed: IOException "
55: + e.getMessage());
56: return returnNullOrFail(e, shouldFail);
57: }
58: }
59:
60: private static Page returnNullOrFail(final Exception e,
61: final boolean shouldFail) {
62: if (shouldFail) {
63: throw new RuntimeException(e);
64: } else {
65: return null;
66: }
67: }
68:
69: // TODO: smell boundary class call back into non-boundary class (xpathHelper) extract out and supply tests
70: public static Object trySelectSingleNodeByXPath(
71: final String xpathStr, final Page currentResp,
72: final Step step) {
73: try {
74: final XPathHelper xpathHelper = step.getContext()
75: .getXPathHelper();
76: final XPath xpath = xpathHelper.getXPath(currentResp,
77: xpathStr);
78: return xpath.selectSingleNode(xpathHelper
79: .getDocument(currentResp));
80: } catch (final JaxenException e) {
81: throw new StepExecutionException(
82: "Error processing xpath \"" + xpathStr + "\".",
83: step, e);
84: }
85: }
86: }
|