01: // Copyright © 2002-2005 Canoo Engineering AG, Switzerland.
02: package com.canoo.webtest.steps.request;
03:
04: import com.canoo.webtest.engine.StepFailedException;
05: import com.canoo.webtest.extension.StoreElementAttribute;
06: import com.gargoylesoftware.htmlunit.Page;
07: import com.gargoylesoftware.htmlunit.html.ClickableElement;
08: import com.gargoylesoftware.htmlunit.html.HtmlElement;
09: import com.gargoylesoftware.htmlunit.html.HtmlPage;
10: import org.apache.log4j.Logger;
11: import org.jaxen.JaxenException;
12:
13: import java.io.IOException;
14:
15: /**
16: * Clicks an html element determined by its id or xpath.<p>
17: *
18: * @author Marc Guillemot
19: * @author Paul King
20: * @webtest.step category="Extension"
21: * name="clickElement"
22: * alias="click"
23: * description="Clicks an <key>HTML</key> element identified by its <em>id</em> or <em>xpath</em>. If the click triggers the load of a new page, then this page becomes the current one."
24: */
25: public class ClickElement extends AbstractTargetAction {
26: private static final Logger LOG = Logger
27: .getLogger(ClickElement.class);
28: private String fHtmlId;
29: private String fXPath;
30:
31: public String getHtmlId() {
32: return fHtmlId;
33: }
34:
35: /**
36: * Sets the id attribute of the element to click.<p>
37: *
38: * @param str the new value
39: * @webtest.parameter required="yes/no"
40: * description="The id of the html element to click on. One of <em>htmlId</em> or <em>xPath</em> must be set."
41: */
42: public void setHtmlId(final String str) {
43: fHtmlId = str;
44: }
45:
46: public String getXpath() {
47: return fXPath;
48: }
49:
50: /**
51: * Sets the XPath used to identify the element to click.<p>
52: *
53: * @param path the new value
54: * @webtest.parameter required="yes/no"
55: * description="The XPath identifying the html element to click on. One of <em>htmlId</em> or <em>xPath</em> must be set."
56: */
57: public void setXpath(final String path) {
58: fXPath = path;
59: }
60:
61: protected void verifyParameters() {
62: super .verifyParameters();
63: nullResponseCheck();
64: paramCheck(getHtmlId() == null && getXpath() == null,
65: "\"htmlId\" or \"xPath\" must be set!");
66: paramCheck(getHtmlId() != null && getXpath() != null,
67: "Only one from \"htmlId\" and \"xPath\" can be set!");
68: }
69:
70: protected Page findTarget() throws JaxenException, IOException {
71: final HtmlPage currentResp = getContext()
72: .getCurrentHtmlResponse(this );
73: final HtmlElement element = StoreElementAttribute.findElement(
74: currentResp, getHtmlId(), getXpath(), LOG, this );
75: if (!(element instanceof ClickableElement)) {
76: throw new StepFailedException("Element is not clickable ("
77: + element + ")", this );
78: }
79: return ((ClickableElement) element).click();
80: }
81:
82: protected String getLogMessageForTarget() {
83: return "by clickElement with "
84: + ((getXpath() == null) ? "id: " + getHtmlId()
85: : "xpath: " + getXpath());
86: }
87:
88: }
|