aboutsummaryrefslogtreecommitdiff
path: root/library/src/org/hamcrest/xml/HasXPath.java
blob: 742935b453f23ab8fd362c565f02cce1c40725a5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package org.hamcrest.xml;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.w3c.dom.Node;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

/**
 * Applies a Matcher to a given XML Node in an existing XML Node tree, specified by an XPath expression.
 *
 * @author Joe Walnes
 */
public class HasXPath extends TypeSafeMatcher<Node> {

    private final Matcher<String> valueMatcher;
    private final XPathExpression compiledXPath;
    private final String xpathString;

    /**
     * @param xPathExpression XPath expression.
     * @param valueMatcher Matcher to use at given XPath.
     *                     May be null to specify that the XPath must exist but the value is irrelevant.
     */
    public HasXPath(String xPathExpression, Matcher<String> valueMatcher) {
        try {
            XPath xPath = XPathFactory.newInstance().newXPath();
            compiledXPath = xPath.compile(xPathExpression);
            this.xpathString = xPathExpression;
            this.valueMatcher = valueMatcher;
        } catch (XPathExpressionException e) {
            throw new IllegalArgumentException("Invalid XPath : " + xPathExpression, e);
        }
    }

    public boolean matchesSafely(Node item) {
        try {
            String result = (String) compiledXPath.evaluate(item, XPathConstants.STRING);
            if (result == null) {
                return false;
            } else if (valueMatcher == null) {
                return !result.equals("");
            } else {
                return valueMatcher.matches(result);
            }
        } catch (XPathExpressionException e) {
            return false;
        }
    }

    public void describeTo(Description description) {
        description.appendText("an XML document with XPath ").appendText(xpathString);
        if (valueMatcher != null) {
            description.appendText(" ").appendDescriptionOf(valueMatcher);
        }
    }
    
    @Factory
    public static Matcher<Node> hasXPath(String xPath, Matcher<String> valueMatcher) {
        return new HasXPath(xPath, valueMatcher);
    }

    @Factory
    public static Matcher<Node> hasXPath(String xPath) {
        return hasXPath(xPath, null);
    }

}