Search in sources :

Example 1 with XPathExpression

use of org.springframework.xml.xpath.XPathExpression in project spring-integration-samples by spring-projects.

the class TrafficHttpConverter method read.

public Traffic read(Class<? extends Traffic> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
    Traffic traffic = new Traffic();
    try {
        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputMessage.getBody());
        XPathExpression titlesXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Title");
        List<Node> titles = titlesXp.evaluateAsNodeList(document);
        XPathExpression descXp = XPathExpressionFactory.createXPathExpression("/ResultSet/Result[@type='incident']/Description");
        List<Node> description = descXp.evaluateAsNodeList(document);
        int counter = 0;
        for (Node node : titles) {
            traffic.addIncident(((Element) node).getTextContent(), ((Element) description.get(counter++)).getTextContent());
        }
    } catch (Exception e) {
        throw new HttpMessageConversionException("Failed to convert response to: " + clazz, e);
    }
    return traffic;
}
Also used : XPathExpression(org.springframework.xml.xpath.XPathExpression) Node(org.w3c.dom.Node) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) Document(org.w3c.dom.Document) HttpMessageConversionException(org.springframework.http.converter.HttpMessageConversionException) IOException(java.io.IOException) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) HttpMessageNotReadableException(org.springframework.http.converter.HttpMessageNotReadableException)

Example 2 with XPathExpression

use of org.springframework.xml.xpath.XPathExpression in project spring-integration by spring-projects.

the class XPathUtils method evaluate.

/**
 * Utility method to evaluate an xpath on the provided object.
 * Delegates evaluation to an {@link XPathExpression}.
 * Note this method provides the {@code #xpath()} SpEL function.
 *
 * @param o         the xml Object for evaluaton.
 * @param xpath     an 'xpath' expression String.
 * @param resultArg an optional parameter to represent the result type of the xpath evaluation.
 *                  Only one argument is allowed, which can be an instance of {@link org.springframework.xml.xpath.NodeMapper} or
 *                  one of these String constants: "string", "boolean", "number", "node" or "node_list".
 * @param <T>       The required return type.
 * @return the result of the xpath expression evaluation.
 * @throws IllegalArgumentException - if the provided arguments aren't appropriate types or values;
 * @throws MessagingException - if the provided object can't be converted to a {@link Node};
 * @throws XPathException - if the xpath expression can't be evaluated.
 */
@SuppressWarnings({ "unchecked" })
public static <T> T evaluate(Object o, String xpath, Object... resultArg) {
    Object resultType = null;
    if (resultArg != null && resultArg.length > 0) {
        Assert.isTrue(resultArg.length == 1, "'resultArg' can contains only one element.");
        Assert.noNullElements(resultArg, "'resultArg' can't contains 'null' elements.");
        resultType = resultArg[0];
    }
    XPathExpression expression = XPathExpressionFactory.createXPathExpression(xpath);
    Node node = converter.convertToNode(o);
    if (resultType == null) {
        return (T) expression.evaluateAsString(node);
    } else if (resultType instanceof NodeMapper<?>) {
        return (T) expression.evaluateAsObject(node, (NodeMapper<?>) resultType);
    } else if (resultType instanceof String && RESULT_TYPES.contains(resultType)) {
        String resType = (String) resultType;
        if (DOCUMENT_LIST.equals(resType)) {
            List<Node> nodeList = (List<Node>) XPathEvaluationType.NODE_LIST_RESULT.evaluateXPath(expression, node);
            try {
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                List<Node> documents = new ArrayList<Node>(nodeList.size());
                for (Node n : nodeList) {
                    Document document = documentBuilder.newDocument();
                    document.appendChild(document.importNode(n, true));
                    documents.add(document);
                }
                return (T) documents;
            } catch (ParserConfigurationException e) {
                throw new XPathException("Unable to create 'documentBuilder'.", e);
            }
        } else {
            XPathEvaluationType evaluationType = XPathEvaluationType.valueOf(resType.toUpperCase() + "_RESULT");
            return (T) evaluationType.evaluateXPath(expression, node);
        }
    } else {
        throw new IllegalArgumentException("'resultArg[0]' can be an instance of 'NodeMapper<?>' " + "or one of supported String constants: " + RESULT_TYPES);
    }
}
Also used : XPathExpression(org.springframework.xml.xpath.XPathExpression) XPathException(org.springframework.xml.xpath.XPathException) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ArrayList(java.util.ArrayList) List(java.util.List) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 3 with XPathExpression

use of org.springframework.xml.xpath.XPathExpression in project spring-integration by spring-projects.

the class XPathExpressionParserTests method testStringExpressionWithNamespaceInnerBean.

@Test
public void testStringExpressionWithNamespaceInnerBean() throws Exception {
    StringBuilder xmlDoc = new StringBuilder("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name'>").append("    <map><entry key='ns1' value='www.example.org' /></map>").append("</si-xml:xpath-expression>");
    XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString());
    assertEquals("outputOne", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
    assertEquals("", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
Also used : XPathExpression(org.springframework.xml.xpath.XPathExpression) Test(org.junit.Test)

Example 4 with XPathExpression

use of org.springframework.xml.xpath.XPathExpression in project spring-integration by spring-projects.

the class XPathExpressionParserTests method testStringExpressionWithNamespaceMapReference.

@Test
public void testStringExpressionWithNamespaceMapReference() throws Exception {
    StringBuffer xmlDoc = new StringBuffer("<si-xml:xpath-expression id='xpathExpression' expression='/ns1:name' namespace-map='myNamespaces' />");
    xmlDoc.append("<util:map id='myNamespaces'><entry key='ns1' value='www.example.org' /></util:map>");
    XPathExpression xPathExpression = getXPathExpression(xmlDoc.toString());
    assertEquals("outputOne", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<ns1:name xmlns:ns1='www.example.org'>outputOne</ns1:name>")));
    assertEquals("", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
Also used : XPathExpression(org.springframework.xml.xpath.XPathExpression) Test(org.junit.Test)

Example 5 with XPathExpression

use of org.springframework.xml.xpath.XPathExpression in project spring-integration by spring-projects.

the class XPathExpressionParserTests method testSimpleStringExpression.

@Test
public void testSimpleStringExpression() throws Exception {
    String xmlDoc = "<si-xml:xpath-expression id='xpathExpression' expression='/name' />";
    XPathExpression xPathExpression = getXPathExpression(xmlDoc);
    assertEquals("outputOne", xPathExpression.evaluateAsString(XmlTestUtil.getDocumentForString("<name>outputOne</name>")));
}
Also used : XPathExpression(org.springframework.xml.xpath.XPathExpression) Test(org.junit.Test)

Aggregations

XPathExpression (org.springframework.xml.xpath.XPathExpression)21 Test (org.junit.Test)18 Document (org.w3c.dom.Document)9 GenericMessage (org.springframework.messaging.support.GenericMessage)7 Node (org.w3c.dom.Node)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 List (java.util.List)1 DocumentBuilder (javax.xml.parsers.DocumentBuilder)1 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)1 EndpointMappingKey (org.apache.camel.component.spring.ws.type.EndpointMappingKey)1 EndpointMappingType (org.apache.camel.component.spring.ws.type.EndpointMappingType)1 HttpMessageConversionException (org.springframework.http.converter.HttpMessageConversionException)1 HttpMessageNotReadableException (org.springframework.http.converter.HttpMessageNotReadableException)1 HttpMessageNotWritableException (org.springframework.http.converter.HttpMessageNotWritableException)1 XPathException (org.springframework.xml.xpath.XPathException)1