01: // Copyright © 2002-2005 Canoo Engineering AG, Switzerland.
02: package com.canoo.webtest.steps.store;
03:
04: import java.io.IOException;
05: import java.util.regex.Matcher;
06: import java.util.regex.Pattern;
07:
08: import com.canoo.webtest.engine.StepFailedException;
09: import com.canoo.webtest.util.ConversionUtil;
10:
11: /**
12: * @author Carsten Seibert
13: * @author Marc Guillemot
14: * @author Paul King
15: * @webtest.step category="Core"
16: * name="storeRegEx"
17: * alias="storeregex"
18: * description="This step stores the result of a <key>regex</key> into a property. By specifying a particular group of the <key>regex</key> it is easily to extract only a subset of a given <key>regex</key>."
19: */
20: public class StoreRegExMatch extends BaseStoreStep {
21: private String fText;
22: private String fGroup;
23:
24: public String getText() {
25: return fText;
26: }
27:
28: /**
29: * @webtest.parameter required="true"
30: * description="The <key>regex</key> that shall be evaluated."
31: */
32: public void setText(final String text) {
33: fText = text;
34: }
35:
36: /**
37: * @webtest.parameter required="true"
38: * description="The name of the property that shall receive the extracted value."
39: */
40: public void setProperty(final String property) {
41: super .setProperty(property);
42: }
43:
44: /**
45: * @webtest.parameter required="no"
46: * default="0 (result of the whole expression)"
47: * description="The group within the <key>regex</key> to extract into the specified property."
48: */
49: public void setGroup(final String group) {
50: fGroup = group;
51: }
52:
53: public void doExecute() throws IOException {
54: nullResponseCheck();
55: final String text = getContext().getCurrentResponse()
56: .getWebResponse().getContentAsString(); // possible IOException
57:
58: // "." should match new lines as well, therefore the dotall flag
59: final Matcher matcher = Pattern.compile(getText(),
60: Pattern.DOTALL).matcher(text);
61: if (!matcher.find()) {
62: throw new StepFailedException(
63: "No match for regular expression <" + getText()
64: + ">", this );
65: }
66:
67: final int numberOfGroups = matcher.groupCount();
68:
69: int groupNumber = ConversionUtil.convertToInt(fGroup, 0);
70: if (groupNumber > numberOfGroups) {
71: throw new StepFailedException("Group not found: " + fGroup
72: + " (#groups: " + numberOfGroups + ")", this );
73: }
74:
75: storeProperty(matcher.group(groupNumber));
76: }
77:
78: protected void verifyParameters() {
79: super .verifyParameters();
80: optionalIntegerParamCheck(fGroup, "group", true);
81: emptyParamCheck(getText(),
82: "Regular expression (text attribute)");
83: emptyParamCheck(getProperty(), "property");
84: }
85: }
|