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 String evaluate(InputSource source) throws XPathExpressionException;

Source Link

Document

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

Usage

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

private void doJaxpCompile(OXPath20ExpressionBPEL20 out, Expression source) throws CompilationException {
    String xpathStr;//from w ww. ja  v  a  2s .c  o m
    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  ww.  ja v a2s. c  om*/
    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.synapse.util.xpath.SynapseXPath.java

public String evaluateDOMXPath(MessageContext synCtx) throws XPathExpressionException {

    OMElement element = synCtx.getEnvelope().getBody().getFirstElement();
    OMElement doomElement;//from  w w w  .j  ava  2 s  .c  o m
    if (element == null) {
        doomElement = new DOMSOAPFactory().createOMElement(new QName(""));
    } else {
        doomElement = convertToDOOM(element);
    }
    domXpath.setNamespaceContext(domNamespaceMap);
    domXpath.setXPathFunctionResolver(new GetPropertyFunctionResolver(synCtx));
    domXpath.setXPathVariableResolver(new DOMSynapseXPathVariableResolver(this.getVariableContext(), synCtx));
    XPathExpression expr = domXpath.compile(this.getRootExpr().getText());
    Object result = expr.evaluate(doomElement);

    if (result != null) {
        return result.toString();
    }
    return null;

}

From source file:org.apereo.portal.layout.simple.SimpleLayout.java

@Override
public String findNodeId(XPathExpression xpathExpression) throws PortalException {
    try {//from  ww w  . j av a 2s .co m
        return xpathExpression.evaluate(this.layout);
    } catch (XPathExpressionException e) {
        throw new PortalException("Exception while executing XPathExpression: " + xpathExpression, e);
    }
}

From source file:org.digidoc4j.impl.bdoc.report.ValidationReportTest.java

private void assertXpathHasValue(String expectedValue, String xPathExpression, String xmlInput)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(IOUtils.toInputStream(xmlInput));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile(xPathExpression);
    String evaluate = expr.evaluate(doc);
    assertEquals(expectedValue, evaluate);
}

From source file:org.geoserver.security.xml.XMLRoleService.java

@Override
protected void deserialize() throws IOException {

    try {/*  ww  w  .  j a v  a 2  s . co  m*/
        Document doc = null;
        FileInputStream is = null;
        try {
            is = new FileInputStream(roleFile);
            doc = builder.parse(is);
        } catch (SAXException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }
        if (isValidatingXMLSchema()) {
            XMLValidator.Singleton.validateRoleRegistry(doc);
        }

        XPathExpression expr = XMLXpathFactory.Singleton.getVersionExpressionRR();
        String versioNummer = expr.evaluate(doc);
        RoleXMLXpath xmlXPath = XMLXpathFactory.Singleton.getRoleXMLXpath(versioNummer);

        clearMaps();

        NodeList roleNodes = (NodeList) xmlXPath.getRoleListExpression().evaluate(doc, XPathConstants.NODESET);

        for (int i = 0; i < roleNodes.getLength(); i++) {
            Node roleNode = roleNodes.item(i);

            String roleName = xmlXPath.getRoleNameExpression().evaluate(roleNode);
            NodeList propertyNodes = (NodeList) xmlXPath.getRolePropertiesExpression().evaluate(roleNode,
                    XPathConstants.NODESET);
            Properties roleProps = new Properties();
            for (int j = 0; j < propertyNodes.getLength(); j++) {
                Node propertyNode = propertyNodes.item(j);
                String propertyName = xmlXPath.getPropertyNameExpression().evaluate(propertyNode);
                String propertyValue = xmlXPath.getPropertyValueExpression().evaluate(propertyNode);
                roleProps.put(propertyName, propertyValue);
            }
            GeoServerRole role = createRoleObject(roleName);

            role.getProperties().clear(); // set properties
            for (Object key : roleProps.keySet()) {
                role.getProperties().put(key, roleProps.get(key));
            }
            helper.roleMap.put(roleName, role);
        }
        // second pass for hierarchy
        for (int i = 0; i < roleNodes.getLength(); i++) {
            Node roleNode = roleNodes.item(i);
            String roleName = xmlXPath.getRoleNameExpression().evaluate(roleNode);
            String parentName = xmlXPath.getParentExpression().evaluate(roleNode);
            if (parentName != null && parentName.length() > 0) {
                helper.role_parentMap.put(helper.roleMap.get(roleName), helper.roleMap.get(parentName));
            }
        }

        // user roles
        NodeList userRolesNodes = (NodeList) xmlXPath.getUserRolesExpression().evaluate(doc,
                XPathConstants.NODESET);
        for (int i = 0; i < userRolesNodes.getLength(); i++) {
            Node userRolesNode = userRolesNodes.item(i);
            String userName = xmlXPath.getUserNameExpression().evaluate(userRolesNode);
            SortedSet<GeoServerRole> roleSet = new TreeSet<GeoServerRole>();
            helper.user_roleMap.put(userName, roleSet);
            NodeList userRolesRefNodes = (NodeList) xmlXPath.getUserRolRefsExpression().evaluate(userRolesNode,
                    XPathConstants.NODESET);
            for (int j = 0; j < userRolesRefNodes.getLength(); j++) {
                Node userRolesRefNode = userRolesRefNodes.item(j);
                String roleRef = xmlXPath.getUserRolRefNameExpression().evaluate(userRolesRefNode);
                roleSet.add(helper.roleMap.get(roleRef));
            }
        }

        // group roles
        NodeList groupRolesNodes = (NodeList) xmlXPath.getGroupRolesExpression().evaluate(doc,
                XPathConstants.NODESET);
        for (int i = 0; i < groupRolesNodes.getLength(); i++) {
            Node groupRolesNode = groupRolesNodes.item(i);
            String groupName = xmlXPath.getGroupNameExpression().evaluate(groupRolesNode);
            SortedSet<GeoServerRole> roleSet = new TreeSet<GeoServerRole>();
            helper.group_roleMap.put(groupName, roleSet);
            NodeList groupRolesRefNodes = (NodeList) xmlXPath.getGroupRolRefsExpression()
                    .evaluate(groupRolesNode, XPathConstants.NODESET);
            for (int j = 0; j < groupRolesRefNodes.getLength(); j++) {
                Node groupRolesRefNode = groupRolesRefNodes.item(j);
                String roleRef = xmlXPath.getGroupRolRefNameExpression().evaluate(groupRolesRefNode);
                roleSet.add(helper.roleMap.get(roleRef));
            }
        }
    } catch (XPathExpressionException ex) {
        throw new IOException(ex);
    }
}

From source file:org.geoserver.security.xml.XMLUserGroupService.java

@Override
protected void deserialize() throws IOException {

    try {/*w w  w.j a  v  a 2  s  . c  om*/

        Document doc = null;
        FileInputStream is = null;
        try {
            is = new FileInputStream(userFile);
            doc = builder.parse(is);
        } catch (SAXException e) {
            throw new IOException(e);
        } finally {
            IOUtils.closeQuietly(is);
        }

        if (isValidatingXMLSchema()) {
            XMLValidator.Singleton.validateUserGroupRegistry(doc);
        }

        XPathExpression expr = XMLXpathFactory.Singleton.getVersionExpressionUR();
        String versionNummer = expr.evaluate(doc);
        UserGroupXMLXpath xmlXPath = XMLXpathFactory.Singleton.getUserGroupXMLXpath(versionNummer);

        clearMaps();

        NodeList userNodes = (NodeList) xmlXPath.getUserListExpression().evaluate(doc, XPathConstants.NODESET);
        for (int i = 0; i < userNodes.getLength(); i++) {
            Node userNode = userNodes.item(i);
            boolean userEnabled = Util.convertToBoolean(xmlXPath.getUserEnabledExpression().evaluate(userNode),
                    true);
            String userPassword = null;

            //there doesn't seem to be a way to check for existence of an attribute vs an 
            // attribute being empty, so we check the attribute manually
            if (userNode.getAttributes().getNamedItem(XMLConstants.A_USER_PASSWORD_UR) != null) {
                userPassword = xmlXPath.getUserPasswordExpression().evaluate(userNode);
            }

            String userName = xmlXPath.getUserNameExpression().evaluate(userNode);
            NodeList propertyNodes = (NodeList) xmlXPath.getUserPropertiesExpression().evaluate(userNode,
                    XPathConstants.NODESET);
            Properties userProps = new Properties();
            for (int j = 0; j < propertyNodes.getLength(); j++) {
                Node propertyNode = propertyNodes.item(j);
                String propertyName = xmlXPath.getPropertyNameExpression().evaluate(propertyNode);
                String propertyValue = xmlXPath.getPropertyValueExpression().evaluate(propertyNode);
                userProps.put(propertyName, propertyValue);
            }
            GeoServerUser user = createUserObject(userName, userPassword, userEnabled);

            helper.userMap.put(user.getUsername(), user);
            user.getProperties().clear(); // set properties
            for (Object key : userProps.keySet()) {
                user.getProperties().put(key, userProps.get(key));
                SortedSet<GeoServerUser> propUsers = helper.propertyMap.get(key);
                if (propUsers == null) {
                    propUsers = new TreeSet<GeoServerUser>();
                    helper.propertyMap.put((String) key, propUsers);
                }
                propUsers.add(user);
            }
        }

        NodeList groupNodes = (NodeList) xmlXPath.getGroupListExpression().evaluate(doc,
                XPathConstants.NODESET);
        for (int i = 0; i < groupNodes.getLength(); i++) {
            Node groupNode = groupNodes.item(i);
            String groupName = xmlXPath.getGroupNameExpression().evaluate(groupNode);
            boolean groupEnabled = Util
                    .convertToBoolean(xmlXPath.getGroupEnabledExpression().evaluate(groupNode), true);
            GeoServerUserGroup group = createGroupObject(groupName, groupEnabled);
            helper.groupMap.put(groupName, group);
            NodeList memberNodes = (NodeList) xmlXPath.getGroupMemberListExpression().evaluate(groupNode,
                    XPathConstants.NODESET);
            for (int j = 0; j < memberNodes.getLength(); j++) {
                Node memberNode = memberNodes.item(j);
                String memberName = xmlXPath.getGroupMemberNameExpression().evaluate(memberNode);
                GeoServerUser member = helper.userMap.get(memberName);

                SortedSet<GeoServerUser> members = helper.group_userMap.get(group);
                if (members == null) {
                    members = new TreeSet<GeoServerUser>();
                    helper.group_userMap.put(group, members);
                }
                members.add(member);

                SortedSet<GeoServerUserGroup> userGroups = helper.user_groupMap.get(member);
                if (userGroups == null) {
                    userGroups = new TreeSet<GeoServerUserGroup>();
                    helper.user_groupMap.put(member, userGroups);
                }
                userGroups.add(group);

            }
        }
    } catch (XPathExpressionException ex) {
        throw new IOException(ex);
    }

}

From source file:org.gluu.saml.Response.java

public String getNameId() throws XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();

    xPath.setNamespaceContext(NAMESPACES);
    XPathExpression query = xPath.compile("/samlp:Response/saml:Assertion/saml:Subject/saml:NameID");
    return query.evaluate(xmlDoc);
}

From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java

private String getEvaluationResult(String response)
        throws ParserConfigurationException, SAXException, IOException, XPathExpressionException,
        TransformerException, IllegalAccessException, ClassNotFoundException, InstantiationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);// ww  w . ja v a  2s .co  m
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(new InputSource(new StringReader(response)));
    XPathFactory xPathfactory = XPathFactory.newInstance();
    XPath xpath = xPathfactory.newXPath();
    XPathExpression expr = xpath.compile("/result/value/text()");
    String textValue = expr.evaluate(doc);
    if (!"".equals(textValue))
        return textValue;
    expr = xpath.compile("/result/text()");
    String resultingXmlAsText = expr.evaluate(doc);
    if (!"".equals(resultingXmlAsText.trim()))
        return resultingXmlAsText;
    expr = xpath.compile("/result/child::*");
    Element node = (Element) expr.evaluate(doc, NODE);
    if (node != null) {
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            String nodeName = attribute.getNodeName();
            String nodeValue = attribute.getNodeValue();
            if (XMLNS.equals(nodeName) && SERIALIZED_NAMESPACE.equals(nodeValue)) {
                node.removeAttribute(XMLNS);
            }
        }
        return prettyPrint(node, builder.getDOMImplementation());
    } else {
        return response;
    }
}