Example usage for javax.xml.xpath XPathExpression evaluate

List of usage examples for javax.xml.xpath XPathExpression evaluate

Introduction

In this page you can find the example usage for javax.xml.xpath XPathExpression evaluate.

Prototype

public Object evaluate(InputSource source, QName returnType) throws XPathExpressionException;

Source Link

Document

Evaluate the compiled XPath expression in the context of the specified InputSource and return the result as the specified type.

Usage

From source file:org.apache.camel.builder.xml.XPathBuilder.java

protected Object doInEvaluateAs(XPathExpression xpathExpression, Exchange exchange, QName resultQName) {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Evaluating exchange: " + exchange + " as: " + resultQName);
    }/*w  ww  . j  a  v a2 s. c om*/

    Object answer;

    // set exchange and variable resolver as thread locals for concurrency
    this.exchange.set(exchange);

    try {
        Object document = getDocument(exchange);
        if (resultQName != null) {
            if (document instanceof InputSource) {
                InputSource inputSource = (InputSource) document;
                answer = xpathExpression.evaluate(inputSource, resultQName);
            } else if (document instanceof DOMSource) {
                DOMSource source = (DOMSource) document;
                answer = xpathExpression.evaluate(source.getNode(), resultQName);
            } else {
                answer = xpathExpression.evaluate(document, resultQName);
            }
        } else {
            if (document instanceof InputSource) {
                InputSource inputSource = (InputSource) document;
                answer = xpathExpression.evaluate(inputSource);
            } else if (document instanceof DOMSource) {
                DOMSource source = (DOMSource) document;
                answer = xpathExpression.evaluate(source.getNode());
            } else {
                answer = xpathExpression.evaluate(document);
            }
        }
    } catch (XPathExpressionException e) {
        throw new InvalidXPathExpression(getText(), e);
    }

    if (LOG.isTraceEnabled()) {
        LOG.trace("Done evaluating exchange: " + exchange + " as: " + resultQName + " with result: " + answer);
    }
    return answer;
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

private void processBufferedElement(Level level, UrlRewriteFilterGroupDescriptor config)
        throws XPathExpressionException {
    for (UrlRewriteFilterPathDescriptor selector : config.getSelectors()) {
        if (selector instanceof UrlRewriteFilterApplyDescriptor) {
            XPathExpression path = (XPathExpression) selector.compiledPath(XPATH_COMPILER);
            Object node = path.evaluate(level.scopeNode, XPathConstants.NODE);
            if (node != null) {
                UrlRewriteFilterApplyDescriptor apply = (UrlRewriteFilterApplyDescriptor) selector;
                if (node instanceof Element) {
                    Element element = (Element) node;
                    String value = element.getTextContent();
                    value = filterText(extractQName(element), value, apply.rule());
                    element.setTextContent(value);
                } else if (node instanceof Text) {
                    Text text = (Text) node;
                    String value = text.getWholeText();
                    value = filterText(extractQName(text.getParentNode()), value, apply.rule());
                    text.replaceWholeText(value);
                } else if (node instanceof Attr) {
                    Attr attr = (Attr) node;
                    String value = attr.getValue();
                    value = filterAttribute(extractQName(attr.getOwnerElement()), extractQName(attr), value,
                            apply.rule());
                    attr.setValue(value);
                } else {
                    throw new IllegalArgumentException(RES.unexpectedSelectedNodeType(node));
                }/*from  www  . j  a  v  a 2 s. c  o m*/
            }
        } else if (selector instanceof UrlRewriteFilterDetectDescriptor) {
            XPathExpression path = (XPathExpression) selector.compiledPath(XPATH_COMPILER);
            Object node = path.evaluate(level.scopeNode, XPathConstants.NODE);
            if (node != null) {
                UrlRewriteFilterDetectDescriptor detect = (UrlRewriteFilterDetectDescriptor) selector;
                String value = null;
                if (node instanceof Element) {
                    Element element = (Element) node;
                    value = element.getTextContent();
                } else if (node instanceof Text) {
                    Text text = (Text) node;
                    value = text.getWholeText();
                } else if (node instanceof Attr) {
                    Attr attr = (Attr) node;
                    value = attr.getValue();
                } else {
                    throw new IllegalArgumentException(RES.unexpectedSelectedNodeType(node));
                }
                if (detect.compiledValue(REGEX_COMPILER).matcher(value).matches()) {
                    processBufferedElement(level, detect);
                }
            }
        } else {
            throw new IllegalArgumentException(RES.unexpectedRewritePathSelector(selector));
        }
    }
}

From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlFilterReader.java

protected UrlRewriteFilterPathDescriptor pickFirstMatchingPath(Level level) {
    UrlRewriteFilterPathDescriptor match = null;
    if (level.scopeConfig != null) {
        for (UrlRewriteFilterPathDescriptor selector : level.scopeConfig.getSelectors()) {
            try {
                XPathExpression path = (XPathExpression) selector.compiledPath(XPATH_COMPILER);
                Object node = path.evaluate(level.scopeNode, XPathConstants.NODE);
                if (node != null) {
                    match = selector;/* w ww  . jav  a 2 s . co m*/
                    break;
                }
            } catch (XPathExpressionException e) {
                throw new IllegalArgumentException(selector.path(), e);
            }
        }
    }
    return match;
}

From source file:org.apache.hise.utils.TaskXmlUtils.java

/**
 * Evaluates XPath expression in context of the Task. Expression can contain 
 * XPath Extension functions as defined by WS-HumanTask v1. Following
 * XPath functions are implemented:/*w  ww .  j  av  a2 s.c o m*/
 * <ul>
 * <li> {@link GetInputXPathFunction} </li>
 * <li> {@link GetOutputXPathFunction} </li>
 * </ul>
 * @param xPathString The XPath 1.0 expression.
 * @param returnType The desired return type. See {@link XPathConstants}.
 * @return The result of evaluating the <code>XPath</code> function as an <code>Object</code>.
 */
public Object evaluateXPath(String xPathString, QName returnType) {

    Validate.notNull(xPathString);
    Validate.notNull(returnType);

    Object o = null;

    XPath xpath = createXPathInstance();

    try {

        //TODO create empty document only once
        DocumentBuilder builder = DOMUtils.getDocumentBuilderFactory().newDocumentBuilder();
        Document emptyDocument;
        emptyDocument = builder.parse(new ByteArrayInputStream("<empty/>".getBytes()));
        XPathExpression expr = xpath.compile(xPathString);
        o = expr.evaluate(emptyDocument, returnType);
        __log.debug("evaluated " + o);
        if (o instanceof NodeInfo) {
            NodeInfo o2 = (NodeInfo) o;
            Node o3 = NodeOverNodeInfo.wrap(o2);
            __log.debug("returned " + DOMUtils.domToString(o3));
            return o3;
        } else {
            return o;
        }
    } catch (Exception e) {
        __log.error("Error evaluating XPath: " + xPathString, e);
        throw new RuntimeException(e);
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.runtime.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type)
        throws FaultException, EvaluationException {
    try {/*  w  w  w  .j av  a 2 s. co  m*/
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);

        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) _xpf).getConfiguration());
        XPath xpe = _xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        String xpath = ((OXPath10Expression) cexp).xpath;
        XPathExpression expr = xpe.compile(xpath);
        Node contextNode = ctx.getRootNode();
        if (contextNode == null) {
            contextNode = DOMUtils.newDocument();
        }
        // Create step nodes in XPath in case it is incompletely instantiated
        if (oxpath20.insertMissingData) {
            XPath20ExpressionModifier modifier = new XPath20ExpressionModifier(oxpath20.namespaceCtx,
                    ((XPathFactoryImpl) _xpf).getConfiguration().getNamePool());

            Node temp = ctx.getRootNode();
            if (temp.getLocalName().equals("message") && temp.getNamespaceURI() == null) {
                int startind = xpath.indexOf('.');
                int endind = xpath.indexOf('/');
                if (startind != -1) {
                    String part = null;
                    if (endind != -1) {
                        part = xpath.substring(startind + 1, endind);
                    } else {
                        part = xpath.substring(startind + 1);
                    }
                    Element partElem = DOMUtils.findChildByName((Element) temp, new QName(null, part));

                    if (partElem != null && partElem.getFirstChild() != null) {
                        temp = partElem.getFirstChild();
                    }
                }
            }

            modifier.insertMissingData(expr, temp);
        }
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof XPathException) {
            Throwable th = ((XPathException) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new EvaluationException("Error while executing an XPath expression: " + cause.toString(), cause);
    } catch (WrappedResolverException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new EvaluationException("Error while executing an XPath expression: ", t);
    }
}

From source file:org.apache.ode.bpel.rtrep.v1.xpath10.jaxp.JaxpXPath10ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {/*from  w w  w  . jav a 2  s . c  o  m*/
        OXPath10Expression oxpath = (OXPath10Expression) cexp;
        __log.debug("JAXP runtime: evaluating " + oxpath.xpath);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP runtime: XPathFactory impl = " + xpf.getClass());
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(new JaxpFunctionResolver(ctx, oxpath));
        xpe.setXPathVariableResolver(new JaxpVariableResolver(ctx, oxpath));
        xpe.setNamespaceContext(oxpath.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Object evalResult = expr
                .evaluate(ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode(), type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }

}

From source file:org.apache.ode.bpel.rtrep.v1.xpath20.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {//from   w ww.j  av  a2s  .  c  o m
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        // JAXP based XPath 1.0 runtime does not work anymore after a XPath 2.0 has been evaluated if this is set.
        // System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
        //        "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) xpf).getConfiguration());
        xpf.setXPathFunctionResolver(funcResolver);
        xpf.setXPathVariableResolver(varResolver);
        XPath xpe = xpf.newXPath();
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Node contextNode = ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode();
        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof DynamicError) {
            Throwable th = ((DynamicError) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }
}

From source file:org.apache.ode.bpel.rtrep.v2.xpath20.XPath20ExpressionRuntime.java

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {/*w w  w .  j a va 2 s  .  c o m*/
        OXPath20ExpressionBPEL20 oxpath20 = ((OXPath20ExpressionBPEL20) cexp);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        // JAXP based XPath 1.0 runtime does not work anymore after a XPath 2.0 has been evaluated if this is set.
        // System.setProperty("javax.xml.xpath.XPathFactory:"+XPathConstants.DOM_OBJECT_MODEL,
        //        "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_JDOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_XOM,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_DOM4J,
                "net.sf.saxon.xpath.XPathFactoryImpl");

        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxpath20);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(ctx, oxpath20,
                ((XPathFactoryImpl) xpf).getConfiguration());
        xpf.setXPathFunctionResolver(funcResolver);
        xpf.setXPathVariableResolver(varResolver);
        XPath xpe = xpf.newXPath();
        xpe.setNamespaceContext(oxpath20.namespaceCtx);
        XPathExpression expr = xpe.compile(((OXPath10Expression) cexp).xpath);
        Node contextNode = ctx.getRootNode() == null ? DOMUtils.newDocument() : ctx.getRootNode();
        // Create step nodes in XPath in case it is incompletely instantiated 
        if (oxpath20.insertMissingData) {
            XPath20ExpressionModifier modifier = new XPath20ExpressionModifier(oxpath20.namespaceCtx,
                    ((XPathFactoryImpl) xpf).getConfiguration().getNamePool());
            Node temp = ctx.getRootNode();
            if (temp.getLocalName().equals("message") && temp.getNamespaceURI() == null
                    && temp.getFirstChild() != null && temp.getFirstChild().getFirstChild() != null) {
                modifier.insertMissingData(expr, temp.getFirstChild().getFirstChild());
            } else {
                modifier.insertMissingData(expr, temp);
            }
        }

        Object evalResult = expr.evaluate(contextNode, type);
        if (evalResult != null && __log.isDebugEnabled()) {
            __log.debug("Expression " + cexp.toString() + " generated result " + evalResult + " - type="
                    + evalResult.getClass().getName());
            if (ctx.getRootNode() != null)
                __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
        return evalResult;
    } catch (XPathExpressionException e) {
        // Extracting the real cause from all this wrapping isn't a simple task
        Throwable cause = e.getCause() != null ? e.getCause() : e;
        if (cause instanceof DynamicError) {
            Throwable th = ((DynamicError) cause).getException();
            if (th != null) {
                cause = th;
                if (cause.getCause() != null)
                    cause = cause.getCause();
            }
        }
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, cause.getMessage(),
                cause);
    } catch (WrappedFaultException wre) {
        __log.debug("Could not evaluate expression because of ", wre);
        throw (FaultException) wre.getCause();
    } catch (Throwable t) {
        __log.debug("Could not evaluate expression because of ", t);
        throw new FaultException(cexp.getOwner().constants.qnSubLanguageExecutionFault, t.getMessage(), t);
    }

}

From source file:org.apache.oodt.cas.workflow.gui.model.repo.XmlWorkflowModelRepository.java

protected ModelGraph findGraph(List<FileBasedElement> rootElements, String modelIdRef, Metadata staticMetadata,
        ConcurrentHashMap<String, ConfigGroup> globalConfGroups, Set<String> supportedProcessorIds)
        throws XPathExpressionException, WorkflowException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//*[@id = '" + modelIdRef + "']");
    for (FileBasedElement rootElement : rootElements) {
        Node node = (Node) expr.evaluate(rootElement.getElement(), XPathConstants.NODE);
        if (node != null) {
            return this.loadGraph(rootElements, new FileBasedElement(rootElement.getFile(), (Element) node),
                    staticMetadata, globalConfGroups, supportedProcessorIds);
        }/*from  ww w  .  j  a v a2  s. c o  m*/
    }
    return null;
}

From source file:org.apache.openaz.xacml.std.StdRequestAttributes.java

@Override
public Node getContentNodeByXpathExpression(XPathExpression xpathExpression) {
    if (xpathExpression == null) {
        throw new NullPointerException("Null XPathExpression");
    }//from w w  w  . ja v  a2 s . c  o m
    Node nodeRootThis = this.getContentRoot();
    if (nodeRootThis == null) {
        return null;
    }
    Node matchingNode = null;
    try {
        matchingNode = (Node) xpathExpression.evaluate(nodeRootThis, XPathConstants.NODE);
    } catch (XPathExpressionException ex) {
        this.logger.warn("Failed to retrieve node for \"" + xpathExpression.toString() + "\"", ex);
    }
    return matchingNode;
}