Example usage for javax.xml.xpath XPathConstants BOOLEAN

List of usage examples for javax.xml.xpath XPathConstants BOOLEAN

Introduction

In this page you can find the example usage for javax.xml.xpath XPathConstants BOOLEAN.

Prototype

QName BOOLEAN

To view the source code for javax.xml.xpath XPathConstants BOOLEAN.

Click Source Link

Document

The XPath 1.0 boolean data type.

Maps to Java Boolean .

Usage

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

/**
 * @see org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluateAsBoolean(org.apache.ode.bpel.rtrep.v1.OExpression, org.apache.ode.bpel.explang.EvaluationContext)
 *///from  w  w  w . j  av a  2s .c om
public boolean evaluateAsBoolean(OExpression cexp, EvaluationContext ctx) throws FaultException {
    return (Boolean) evaluate(cexp, ctx, XPathConstants.BOOLEAN);
}

From source file:org.apache.ode.bpel.rtrep.v2.xquery10.runtime.XQuery10ExpressionRuntime.java

/**
 * Cast XQuery sequence into an opaque list 
 *
 * @param type type /*w w w  .  j ava2 s.c  om*/
 * @param result result 
 *
 * @return value
 *
 * @throws XQException XQException 
 */
private Object getResultValue(QName type, XQResultSequence result) throws XQException {
    Document document = DOMUtils.newDocument();
    Object resultValue = null;
    if (XPathConstants.NODESET.equals(type)) {
        List list = new ArrayList();

        while (result.next()) {
            Object itemValue = getItemValue(result.getItem());
            if (itemValue instanceof Node) {
                itemValue = DOMUtils.cloneNode(document, (Node) itemValue);
            }

            if (itemValue != null) {
                list.add(itemValue);
            }
        }

        resultValue = list;
    } else if (XPathConstants.NODE.equals(type)) {
        XQItem item = null;
        if (result.count() > 0) {
            result.first();
            if (result.isOnItem()) {
                item = result.getItem();
            }
        }
        if (item != null) {
            resultValue = getItemValue(item);
            if (resultValue instanceof Node) {
                resultValue = DOMUtils.cloneNode(document, (Node) resultValue);
            }
        }
    } else if (XPathConstants.STRING.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
    } else if (XPathConstants.NUMBER.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
        resultValue = Integer.parseInt((String) resultValue);
    } else if (XPathConstants.BOOLEAN.equals(type)) {
        resultValue = result.getSequenceAsString(new Properties());
        resultValue = Boolean.parseBoolean((String) resultValue);
    }
    return resultValue;
}

From source file:org.apache.solr.client.solrj.embedded.TestSolrProperties.java

public static boolean exists(String xpathStr, Node node) throws XPathExpressionException {
    XPath xpath = xpathFactory.newXPath();
    return (Boolean) xpath.evaluate(xpathStr, node, XPathConstants.BOOLEAN);
}

From source file:org.asqatasun.processor.DOMHandlerImpl.java

/**
 * @deprecated Kept for backward compatibility.
 * @param expr/*from w  ww .ja v a2  s. c  o m*/
 * @return
 */
@Override
@Deprecated
public TestSolution checkEachWithXpath(String expr) {
    Collection<TestSolution> resultSet = new ArrayList<TestSolution>();
    for (Node node : selectedElementList) {
        TestSolution tempResult = TestSolution.PASSED;
        try {
            XPathExpression xPathExpression = xpath.compile(expr);
            Boolean check = (Boolean) xPathExpression.evaluate(node, XPathConstants.BOOLEAN);
            if (!check.booleanValue()) {
                tempResult = TestSolution.FAILED;
                // addSourceCodeRemark(result, node,
                // "wrong value, does not respect xpath expression : " +
                // expr, node.getNodeValue());
            }
        } catch (XPathExpressionException ex) {
            LOGGER.error(ex.getMessage() + " occured requesting " + expr + " on " + ssp.getURI());
            throw new RuntimeException(ex);
        }
        resultSet.add(tempResult);
    }
    return RuleHelper.synthesizeTestSolutionCollection(resultSet);
}

From source file:org.codice.ddf.security.interceptor.AnonymousInterceptor.java

private boolean evaluateExpression(String xml, String xpathStmt) {
    Boolean result = false;//from ww  w  .j  a v a 2s  . co m
    Document document = createDocument(xml);

    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();

    try {
        XPathExpression expr = xpath.compile("boolean(" + xpathStmt + ")");
        result = (Boolean) expr.evaluate(document, XPathConstants.BOOLEAN);
    } catch (XPathExpressionException e) {
        LOGGER.warn("Error processing XPath statement on policy XML.", e);
    }
    return result;
}

From source file:org.jboss.windup.decorator.gate.XPathGateDecorator.java

@Override
protected boolean continueProcessing(XmlMetadata meta) {
    if (meta.getParsedDocument() == null) {
        LOG.warn("Skipping XPathClassifyingDecorator; no parsed doc: "
                + meta.getFilePointer().getAbsolutePath());
        return false;
    }//from www.j a v  a  2  s.c  o  m

    try {
        final Boolean nodes = (Boolean) expression.evaluate(meta.getParsedDocument(), XPathConstants.BOOLEAN);
        if (nodes != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Returning: " + nodes.booleanValue() + " for XPath: " + xpathExpression + " on file: "
                        + meta.getFilePointer().getAbsolutePath());
            }
            return nodes.booleanValue();
        }
    } catch (Exception e) {
        LOG.error("Exception running xpath.", e);
    }

    return false;
}

From source file:org.kuali.rice.edl.impl.components.SelectControlEDLComponent.java

public void updateDOM(Document dom, Element currentDefinitionElement, EDLContext edlContext) {
    Element currentVersion = VersioningPreprocessor.findCurrentVersion(dom);
    XPath xPath = XPathHelper.newXPath(dom);
    try {/*from  w ww  .j  a va 2  s.  c om*/
        NodeList selectFieldDefs = (NodeList) xPath.evaluate(
                "//fieldDef[display/type = 'select' and display/valuesGroup] | //fieldDef[display/type = 'select_refresh' and display/valuesGroup]",
                dom, XPathConstants.NODESET);
        for (int fIndex = 0; fIndex < selectFieldDefs.getLength(); fIndex++) {
            Element fieldDef = (Element) selectFieldDefs.item(fIndex);
            NodeList valuesGroups = (NodeList) xPath.evaluate("./display/valuesGroup", fieldDef,
                    XPathConstants.NODESET);
            for (int index = 0; index < valuesGroups.getLength(); index++) {
                Element valuesGroupElem = (Element) valuesGroups.item(index);
                NodeList dependsOnFields = (NodeList) xPath.evaluate("./dependsOn/field", valuesGroupElem,
                        XPathConstants.NODESET);
                String fieldEvalExpression = "";
                for (int dIndex = 0; dIndex < dependsOnFields.getLength(); dIndex++) {
                    if (!StringUtils.isBlank(fieldEvalExpression)) {
                        fieldEvalExpression += " and ";
                    }
                    Element fieldElem = (Element) dependsOnFields.item(dIndex);
                    String name = fieldElem.getAttribute("name");
                    String value = fieldElem.getTextContent();
                    fieldEvalExpression += "./field[@name='" + name + "']/value = '" + value + "'";
                }
                if ((Boolean) xPath.evaluate(fieldEvalExpression, currentVersion, XPathConstants.BOOLEAN)) {
                    includeValuesGroup(valuesGroupElem);
                } else {
                    // remove the valuesGroup as it did not match
                    valuesGroupElem.getParentNode().removeChild(valuesGroupElem);
                }
            }
        }
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed to evaluate xpath expression.", e);
    }
}

From source file:org.kuali.rice.edl.impl.components.ValidationComponent.java

protected void executeValidation(XPath xpath, Document dom, EDLValidation validation, EDLContext edlContext)
        throws Exception {
    // TODO: in the future, allow this to be pluggable, hardcode for now
    if (XPATH_TYPE.equals(validation.getType())) {
        Boolean result = (Boolean) xpath.evaluate(validation.getExpression(), dom, XPathConstants.BOOLEAN);
        // if validation returns false, we'll flag the error
        if (!result) {
            String key = validation.getKey();
            if (!StringUtils.isEmpty(key)) {
                Map<String, String> fieldErrors = (Map<String, String>) edlContext.getRequestParser()
                        .getAttribute(RequestParser.GLOBAL_FIELD_ERRORS_KEY);
                fieldErrors.put(key, validation.getMessage());

                // set invalid attribute to true on corresponding field
                //TODO remove - handled this in the widgets
                //               Element edlElement = EDLXmlUtils.getEDLContent(dom, false);
                //               Element edlSubElement = EDLXmlUtils.getOrCreateChildElement(edlElement, "data", true);
                //               NodeList versionNodes = edlSubElement.getChildNodes();
                //               for (int i = 0; i < versionNodes.getLength(); i++) {
                //                  Element version = (Element) versionNodes.item(i);
                //                  String current = version.getAttribute("current");
                //                  if (current == "true") {
                //                     NodeList fieldNodes = version.getChildNodes();
                //                     for (int j = 0; j < fieldNodes.getLength(); j++) {
                //                        Element field = (Element) fieldNodes.item(j);
                //                        String fieldName = field.getAttribute("name");
                //                        if(fieldName.equals(key)) {
                //                           field.setAttribute("invalid", "true");
                //                           break;
                //                        }
                //                     }
                //                  }
                //               }

            } else {
                List globalErrors = (List) edlContext.getRequestParser()
                        .getAttribute(RequestParser.GLOBAL_ERRORS_KEY);
                globalErrors.add(validation.getMessage());
            }//from   w w  w.j a v a 2  s. c  om
            edlContext.setInError(true);
        }
    } else {
        throw new WorkflowRuntimeException(
                "Illegal validation type specified.  Only 'xpath' is currently supported.");
    }
}

From source file:org.kuali.rice.kew.rule.xmlrouting.StandardGenericXMLRuleAttribute.java

public boolean isMatch(DocumentContent docContent, List<RuleExtension> ruleExtensions) {
    XPath xpath = null;/*from w ww  .  j a  v a  2  s  .  c o  m*/
    String xPathCacheKey = null;
    RouteNodeInstance rni = docContent.getRouteContext().getNodeInstance();
    if (rni != null) {
        xPathCacheKey = "xPath" + rni.getRouteNodeInstanceId() + "-" + rni.getName();
        if (docContent.getRouteContext().getParameters().containsKey(xPathCacheKey)) {
            xpath = (XPath) docContent.getRouteContext().getParameters().get(xPathCacheKey);
        } else {
            xpath = XPathHelper.newXPath(docContent.getDocument());
            docContent.getRouteContext().getParameters().put(xPathCacheKey, xpath);
        }
    } else {
        xpath = XPathHelper.newXPath(docContent.getDocument());
        docContent.getRouteContext().getParameters().put(xPathCacheKey, xpath);
    }
    WorkflowFunctionResolver resolver = XPathHelper.extractFunctionResolver(xpath);
    resolver.setRuleExtensions(ruleExtensions);
    List<String> xPathExpressionsToEvaluate = extractExpressionsToEvaluate(xpath, docContent, ruleExtensions);
    for (String xPathExpressionToEvaluate : xPathExpressionsToEvaluate) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Evaluating xPath expression: " + xPathExpressionToEvaluate);
        }
        try {
            Boolean match = (Boolean) xpath.evaluate(xPathExpressionToEvaluate, docContent.getDocument(),
                    XPathConstants.BOOLEAN);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Expression match result: " + match);
            }
            if (match != null && !match.booleanValue()) {
                return false;
            }
        } catch (XPathExpressionException e) {
            LOG.error("Error in isMatch ", e);
            throw new RuntimeException(
                    "Error trying to evalute xml content with xpath expression: " + xPathExpressionToEvaluate,
                    e);
        }
    }
    return true;
}

From source file:org.kuali.rice.kew.xml.DocumentTypeXmlParser.java

private RouteNode createRouteNode(RouteNode previousRouteNode, String nodeName, Node routePathNode,
        Node routeNodesNode, DocumentType documentType, RoutePathContext context)
        throws XPathExpressionException, XmlException, GroupNotFoundException {
    if (nodeName == null)
        return null;

    Node currentNode;//from ww w .  java2  s .co m
    context.nodeXPath += "//" + "*[@name = '" + nodeName + "']";
    context.nodeQName += nodeName + ":";

    try {
        currentNode = (Node) getXPath().evaluate(context.nodeXPath + "//" + "*[@name = '" + nodeName + "']",
                routePathNode, XPathConstants.NODE);
        if (currentNode == null) {
            findNodeOnXPath(nodeName, context, routePathNode);
            currentNode = (Node) getXPath().evaluate(context.nodeXPath + "//" + "*[@name = '" + nodeName + "']",
                    routePathNode, XPathConstants.NODE);
        }
    } catch (XPathExpressionException xpee) {
        LOG.error("Error obtaining routePath for routeNode", xpee);
        throw xpee;
    }

    if (currentNode == null) {
        String message = "Next node '" + nodeName + "' for node '" + previousRouteNode.getRouteNodeName()
                + "' not found!";
        LOG.error(message);
        throw new XmlException(message);
    }

    context.nodeXPath += "//" + "*[@name = '" + nodeName + "']";
    context.nodeQName += nodeName + ":";
    LOG.debug("nodeQNme:" + context.nodeQName);
    boolean nodeIsABranch;

    try {
        nodeIsABranch = ((Boolean) getXPath().evaluate("self::node()[local-name() = 'branch']", currentNode,
                XPathConstants.BOOLEAN)).booleanValue();
    } catch (XPathExpressionException xpee) {
        LOG.error("Error testing whether node is a branch", xpee);
        throw xpee;
    }

    if (nodeIsABranch) {
        throw new XmlException("Next node cannot be a branch node");
    }

    String localName;

    try {
        localName = (String) getXPath().evaluate("local-name(.)", currentNode, XPathConstants.STRING);
    } catch (XPathExpressionException xpee) {
        LOG.error("Error obtaining node local-name", xpee);
        throw xpee;
    }

    RouteNode currentRouteNode = null;

    if (nodesMap.containsKey(context.nodeQName)) {
        currentRouteNode = (RouteNode) nodesMap.get(context.nodeQName);
    } else {
        String nodeExpression = ".//*[@name='" + nodeName + "']";
        currentRouteNode = makeRouteNodePrototype(localName, nodeName, nodeExpression, routeNodesNode,
                documentType, context);
    }

    if ("split".equalsIgnoreCase(localName)) {
        getSplitNextNodes(currentNode, routePathNode, currentRouteNode, routeNodesNode, documentType,
                cloneContext(context));
    }

    if (previousRouteNode != null) {
        previousRouteNode.getNextNodes().add(currentRouteNode);
        nodesMap.put(context.previousNodeQName, previousRouteNode);
        currentRouteNode.getPreviousNodes().add(previousRouteNode);
    }

    String nextNodeName = null;
    boolean hasNextNodeAttrib;

    try {
        hasNextNodeAttrib = ((Boolean) getXPath().evaluate(NEXT_NODE_EXP, currentNode, XPathConstants.BOOLEAN))
                .booleanValue();
    } catch (XPathExpressionException xpee) {
        LOG.error("Error obtaining node nextNode attrib", xpee);
        throw xpee;
    }

    if (hasNextNodeAttrib) {
        // if the node has a nextNode but is not a split node, the nextNode is used for its node
        if (!"split".equalsIgnoreCase(localName)) {
            try {
                nextNodeName = (String) getXPath().evaluate(NEXT_NODE_EXP, currentNode, XPathConstants.STRING);
            } catch (XPathExpressionException xpee) {
                LOG.error("Error obtaining node nextNode attrib", xpee);
                throw xpee;
            }

            context.previousNodeQName = context.nodeQName;
            createRouteNode(currentRouteNode, nextNodeName, routePathNode, routeNodesNode, documentType,
                    cloneContext(context));
        } else {
            // if the node has a nextNode but is a split node, the nextNode must be used for that split node's join node
            nodesMap.put(context.nodeQName, currentRouteNode);
        }

    } else {
        // if the node has no nextNode of its own and is not a join which gets its nextNode from its parent split node
        if (!"join".equalsIgnoreCase(localName)) {
            nodesMap.put(context.nodeQName, currentRouteNode);

        } else { // if join has a parent nextNode (on its split node) and join has not already walked this path
            boolean parentHasNextNodeAttrib;
            try {
                parentHasNextNodeAttrib = ((Boolean) getXPath().evaluate(PARENT_NEXT_NODE_EXP, currentNode,
                        XPathConstants.BOOLEAN)).booleanValue();
            } catch (XPathExpressionException xpee) {
                LOG.error("Error obtaining parent node nextNode attrib", xpee);
                throw xpee;
            }

            if (parentHasNextNodeAttrib && !nodesMap.containsKey(context.nodeQName)) {
                try {
                    nextNodeName = (String) getXPath().evaluate(PARENT_NEXT_NODE_EXP, currentNode,
                            XPathConstants.STRING);
                } catch (XPathExpressionException xpee) {
                    LOG.error("Error obtaining parent node nextNode attrib", xpee);
                    throw xpee;
                }

                context.previousNodeQName = context.nodeQName;
                createRouteNode(currentRouteNode, nextNodeName, routePathNode, routeNodesNode, documentType,
                        cloneContext(context));
            } else {
                // if join's parent split node does not have a nextNode
                nodesMap.put(context.nodeQName, currentRouteNode);
            }
        }
    }

    // handle nextAppDocStatus route node attribute
    String nextDocStatusName = null;
    boolean hasNextDocStatus;

    try {
        hasNextDocStatus = ((Boolean) getXPath().evaluate(NEXT_DOC_STATUS_EXP, currentNode,
                XPathConstants.BOOLEAN)).booleanValue();
    } catch (XPathExpressionException xpee) {
        LOG.error("Error obtaining node nextAppDocStatus attrib", xpee);
        throw xpee;
    }

    if (hasNextDocStatus) {
        try {
            nextDocStatusName = (String) getXPath().evaluate(NEXT_DOC_STATUS_EXP, currentNode,
                    XPathConstants.STRING);
        } catch (XPathExpressionException xpee) {
            LOG.error("Error obtaining node nextNode attrib", xpee);
            throw xpee;
        }

        //validate against allowable values if defined
        if (documentType.getValidApplicationStatuses() != null
                && documentType.getValidApplicationStatuses().size() > 0) {
            Iterator iter = documentType.getValidApplicationStatuses().iterator();
            boolean statusValidated = false;

            while (iter.hasNext()) {
                ApplicationDocumentStatus myAppDocStat = (ApplicationDocumentStatus) iter.next();
                if (nextDocStatusName.compareToIgnoreCase(myAppDocStat.getStatusName()) == 0) {
                    statusValidated = true;
                    break;
                }
            }

            if (!statusValidated) {
                XmlException xpee = new XmlException(
                        "AppDocStatus value " + nextDocStatusName + " not allowable.");
                LOG.error("Error validating nextAppDocStatus name: " + nextDocStatusName
                        + " against acceptable values.", xpee);
                throw xpee;
            }
        }

        currentRouteNode.setNextDocStatus(nextDocStatusName);
    }

    return currentRouteNode;
}