Example usage for javax.xml.xpath XPath setXPathFunctionResolver

List of usage examples for javax.xml.xpath XPath setXPathFunctionResolver

Introduction

In this page you can find the example usage for javax.xml.xpath XPath setXPathFunctionResolver.

Prototype

public void setXPathFunctionResolver(XPathFunctionResolver resolver);

Source Link

Document

Establish a function resolver.

Usage

From source file:XPathResolver.java

public static void main(String[] args) {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    // Set the NamespaceContext
    xpath.setNamespaceContext(new MyNamespaceContext());
    // Set the function resolver
    xpath.setXPathFunctionResolver(new MyFunctionResolver());
    // Set the variable resolver
    xpath.setXPathVariableResolver(new MyVariableResolver());

    Object result = null;/*  ww w.  j  a v a 2  s .c  o m*/
    try {
        result = xpath.evaluate(EXPR, (Object) null, XPathConstants.NUMBER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    // The evaluation result is 9.0.
    System.out.println("The evaluation result: " + result);
}

From source file:ExtensionFunctionResolver.java

public static void main(String[] args) throws Exception {
    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    // set the NamespaceContext to 
    // org.apache.xalan.extensions.ExtensionNamespaceContext
    xpath.setNamespaceContext(new ExtensionNamespaceContext());

    // set the XPathFunctionResolver to 
    // org.apache.xalan.extensions.XPathFunctionResolverImpl
    xpath.setXPathFunctionResolver(new XPathFunctionResolverImpl());

    Object result = null;/*ww w  . j  ava  2 s . c  o m*/
    // Evaluate the XPath expression "math:max(/doc/num)" against 
    // the input document numlist.xml
    InputSource context = new InputSource("numlist.xml");
    result = xpath.evaluate(EXPR1, context, XPathConstants.NUMBER);
    System.out.println(EXPR1 + " = " + result);

    // Evaluate the XPath expression "java:ExtensionTest.test('Bob')"
    result = xpath.evaluate(EXPR2, context, XPathConstants.STRING);
    System.out.println(EXPR2 + " = " + result);
}

From source file:Main.java

private static XPath createXPath(NamespaceContext namespaceContext, XPathFunctionResolver functionResolver) {
    XPath xPath = XPathFactory.newInstance().newXPath();
    if (namespaceContext != null) {
        xPath.setNamespaceContext(namespaceContext);
    }/*from   ww  w .ja v  a 2 s  .co  m*/
    if (functionResolver != null) {
        xPath.setXPathFunctionResolver(functionResolver);
    }
    return xPath;
}

From source file:Main.java

/**
 * Create a new {@link XPath} with the passed variable resolver, function
 * resolver and namespace context./*from www.  j a  va 2 s  .  co m*/
 * 
 * @param aXPathFactory
 *        The XPath factory object to use. May not be <code>null</code>.
 * @param aVariableResolver
 *        Variable resolver to be used. May be <code>null</code>.
 * @param aFunctionResolver
 *        Function resolver to be used. May be <code>null</code>.
 * @param aNamespaceContext
 *        Namespace context to be used. May be <code>null</code>.
 * @return The created non-<code>null</code> {@link XPath} object
 */
@Nonnull
public static XPath createNewXPath(@Nonnull final XPathFactory aXPathFactory,
        @Nullable final XPathVariableResolver aVariableResolver,
        @Nullable final XPathFunctionResolver aFunctionResolver,
        @Nullable final NamespaceContext aNamespaceContext) {
    if (aXPathFactory == null)
        throw new NullPointerException("XPathFactory");

    final XPath aXPath = aXPathFactory.newXPath();
    if (aVariableResolver != null)
        aXPath.setXPathVariableResolver(aVariableResolver);
    if (aFunctionResolver != null)
        aXPath.setXPathFunctionResolver(aFunctionResolver);
    if (aNamespaceContext != null)
        aXPath.setNamespaceContext(aNamespaceContext);
    return aXPath;
}

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

protected XPathExpression createXPathExpression()
        throws XPathExpressionException, XPathFactoryConfigurationException {
    XPath xPath = getXPathFactory().newXPath();

    xPath.setNamespaceContext(getNamespaceContext());
    xPath.setXPathVariableResolver(getVariableResolver());

    XPathFunctionResolver parentResolver = getFunctionResolver();
    if (parentResolver == null) {
        parentResolver = xPath.getXPathFunctionResolver();
    }// www.j a v a 2s . co  m
    xPath.setXPathFunctionResolver(createDefaultFunctionResolver(parentResolver));
    return xPath.compile(text);
}

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

/**
 * Creates {@link XPath} aware of request namespaces.
 *//*from ww  w  . j a  v  a2 s .  co  m*/
synchronized XPath createXPathInstance() {

    XPath xpath = this.xPathFactory.newXPath();

    xpath.setNamespaceContext(this.namespaceContext);
    xpath.setXPathFunctionResolver(new XPathFunctionResolver() {

        public XPathFunction resolveFunction(QName functionName, int arity) {

            if (functionName == null) {
                throw new NullPointerException("The function name cannot be null.");
            }

            if (functionName.equals(new QName("http://www.example.org/WS-HT", "getInput", "htd"))) {

                return new GetXPathFunction(input);
            }

            if (functionName.equals(new QName("http://www.example.org/WS-HT", "getOutput", "htd"))) {

                return new GetXPathFunction(output);
            }

            return null;
        }
    });

    return xpath;
}

From source file:org.apache.ode.bpel.compiler.v1.xpath10.jaxp.JaxpXPath10ExpressionCompilerImpl.java

/**
 * Verifies validity of a xpath expression.
 *//*w  w  w.ja v  a  2s.c  o  m*/
protected void doJaxpCompile(OXPath10Expression out, Expression source) throws CompilationException {
    String xpathStr;
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XPath string and xpath node are both null");
    }

    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.errXPathSyntax(xpathStr));
    }

    try {
        __log.debug("JAXP compile: xpath = " + xpathStr);
        // use default XPath implementation
        XPathFactory xpf = XPathFactory.newInstance();
        __log.debug("JAXP compile: XPathFactory impl = " + xpf.getClass());
        XPath xpath = xpf.newXPath();
        xpath.setXPathFunctionResolver(
                new JaxpFunctionResolver(_compilerContext, out, source.getNamespaceContext(), _bpelNsURI));
        xpath.setXPathVariableResolver(new JaxpVariableResolver(_compilerContext, out));
        xpath.setNamespaceContext(source.getNamespaceContext());
        XPathExpression xpe = xpath.compile(xpathStr);
        // dummy evaluation to resolve variables and functions (hopefully complete...)
        xpe.evaluate(DOMUtils.newDocument());
        out.xpath = xpathStr;
    } catch (XPathExpressionException e) {
        throw new CompilationException(__msgs.errUnexpectedCompilationError(e.getMessage()), e);
    }
}

From source file:org.apache.ode.bpel.compiler.v1.xpath20.XPath20ExpressionCompilerImpl.java

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;//  w  ww  . j  a  v a2s . com
    Node node = source.getExpression();
    if (node == null) {
        throw new IllegalStateException("XPath string and xpath node are both null");
    }
    if (node.getNodeType() != Node.TEXT_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    out.xpath = xpathStr;
    try {
        __log.debug("Compiling expression " + xpathStr);
        System.setProperty("javax.xml.xpath.XPathFactory:" + NamespaceConstant.OBJECT_MODEL_SAXON,
                "net.sf.saxon.xpath.XPathFactoryImpl");
        XPathFactory xpf = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON);
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(_compilerContext, out);
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(source.getNamespaceContext());
        XPathExpression expr = xpe.compile(xpathStr);
        // evaluate the expression so as to initialize the variables
        try {
            expr.evaluate(node);
        } catch (XPathExpressionException xpee) {
            // swallow errors caused by uninitialized variable 
        }
        for (String varExpr : extractVariableExprs(xpathStr)) {
            expr = xpe.compile(varExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable 
            }
        }
    } catch (XPathFactoryConfigurationException xpfce) {
        __log.debug(xpfce);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (XPathExpressionException e) {
        __log.debug(e);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

From source file:org.apache.ode.bpel.elang.xpath20.compiler.XPath20ExpressionCompilerImpl.java

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;//from  w w w  .j a v  a 2s.c  o m
    Node node = source.getExpression();
    if (node == null) {
        throw new CompilationException(__msgs.errEmptyExpression(source.getURI(),
                new QName(source.getElement().getNamespaceURI(), source.getElement().getNodeName())));
    }
    if (node.getNodeType() != Node.TEXT_NODE && node.getNodeType() != Node.CDATA_SECTION_NODE) {
        throw new CompilationException(__msgs.errUnexpectedNodeTypeForXPath(DOMUtils.domToString(node)));
    }
    xpathStr = node.getNodeValue();
    xpathStr = xpathStr.trim();
    if (xpathStr.length() == 0) {
        throw new CompilationException(__msgs.warnXPath20Syntax(DOMUtils.domToString(node), "empty string"));
    }

    out.xpath = xpathStr;
    try {
        __log.debug("Compiling expression " + xpathStr);
        XPathFactory xpf = new XPathFactoryImpl();
        JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(_compilerContext, out,
                source.getNamespaceContext(), _bpelNS);
        JaxpVariableResolver varResolver = new JaxpVariableResolver(_compilerContext, out);
        XPath xpe = xpf.newXPath();
        xpe.setXPathFunctionResolver(funcResolver);
        xpe.setXPathVariableResolver(varResolver);
        xpe.setNamespaceContext(source.getNamespaceContext());
        XPathExpression expr = xpe.compile(xpathStr);
        // evaluate the expression so as to initialize the variables
        try {
            expr.evaluate(node);
        } catch (XPathExpressionException xpee) {
            // swallow errors caused by uninitialized variable
        }
        for (String varExpr : extractVariableExprs(xpathStr)) {
            expr = xpe.compile(varExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
        for (String functionExpr : extractFunctionExprs(xpathStr)) {
            expr = xpe.compile(functionExpr);
            try {
                expr.evaluate(node);
            } catch (XPathExpressionException xpee) {
                // swallow errors caused by uninitialized variable
            }
        }
    } catch (XPathExpressionException e) {
        __log.debug(e);
        __log.info("Couldn't validate properly expression " + xpathStr);
    } catch (WrappedResolverException wre) {
        if (wre._compilationMsg != null)
            throw new CompilationException(wre._compilationMsg, wre);
        if (wre.getCause() instanceof CompilationException)
            throw (CompilationException) wre.getCause();
        throw wre;
    }
}

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 ww  .  j ava 2  s .c  o  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);
    }
}