Example usage for javax.xml.xpath XPath compile

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

Introduction

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

Prototype

public XPathExpression compile(String expression) throws XPathExpressionException;

Source Link

Document

Compile an XPath expression for later evaluation.

Usage

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

private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type) throws FaultException {
    try {//  www. ja  va 2s .co 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);
        }//  ww w.  j a va 2  s .  co m
    }
    return null;
}

From source file:org.apache.openmeetings.cli.ConnectionPropertiesPatcher.java

private static Attr getConnectionProperties(Document doc) throws Exception {
    XPath xPath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xPath
            .compile("/persistence/persistence-unit/properties/property[@name='openjpa.ConnectionProperties']");

    Element element = (Element) expr.evaluate(doc, XPathConstants.NODE);
    return element.getAttributeNode("value");
}

From source file:org.apache.stratos.load.balancer.conf.configurator.SynapseConfigurator.java

/**
 * Configure main sequence send mediator endpoint.
 *
 * @param configuration  Load balancer configuration.
 * @param inputFilePath  Input file path.
 * @param outputFilePath Output file path.
 *///w  w  w  .  j  a  v a  2 s  .  c o  m
public static void configureMainSequence(LoadBalancerConfiguration configuration, String inputFilePath,
        String outputFilePath) {
    try {
        if (log.isInfoEnabled()) {
            log.info("Configuring synapse main sequence...");
        }
        if (log.isDebugEnabled()) {
            log.debug(String.format("Reading synapse main sequence: %s", inputFilePath));
        }
        File inputFile = new File(inputFilePath);
        if (!inputFile.exists()) {
            throw new RuntimeException(String.format("File not found: %s", inputFilePath));
        }
        FileInputStream file = new FileInputStream(inputFile);
        DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document xmlDocument = builder.parse(file);
        XPath xPath = XPathFactory.newInstance().newXPath();

        String expression = "/sequence/in/send/endpoint/class/parameter";
        if (log.isDebugEnabled()) {
            log.debug(String.format("xpath expression = %s", expression));
        }
        boolean updated = false;
        NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            Node parameter = node.getAttributes().getNamedItem("name");
            if (parameter.getNodeValue().equals("algorithmClassName")) {
                String defaultAlgorithmName = configuration.getDefaultAlgorithmName();
                if (StringUtils.isBlank(defaultAlgorithmName)) {
                    throw new RuntimeException(
                            "Default algorithm name not found in load balancer configuration");
                }
                Algorithm defaultAlgorithm = configuration.getAlgorithm(defaultAlgorithmName);
                if (defaultAlgorithm == null) {
                    throw new RuntimeException("Default algorithm not found in load balancer configuration");
                }
                String algorithmClassName = defaultAlgorithm.getClassName();
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Setting algorithm-class-name = %s", algorithmClassName));
                }
                node.setTextContent(algorithmClassName);
                updated = true;
            } else if (parameter.getNodeValue().equals("failover")) {
                String value = String.valueOf(configuration.isFailOverEnabled());
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Setting failover = %s", value));
                }
                node.setTextContent(value);
                updated = true;
            } else if (parameter.getNodeValue().equals("sessionAffinity")) {
                String value = String.valueOf(configuration.isSessionAffinityEnabled());
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Setting session-affinity = %s", value));
                }
                node.setTextContent(value);
                updated = true;
            } else if (parameter.getNodeValue().equals("sessionTimeout")) {
                String value = String.valueOf(configuration.getSessionTimeout());
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Setting session-timeout = %s", value));
                }
                node.setTextContent(value);
                updated = true;
            }
        }
        if (updated) {
            if (log.isDebugEnabled()) {
                log.debug(String.format("Updating synapse main sequence: %s", outputFilePath));
            }
            write(xmlDocument, outputFilePath);
            if (log.isInfoEnabled()) {
                log.info("Synapse main sequence configured successfully");
            }
        } else {
            throw new RuntimeException(
                    String.format("Send mediator endpoint configuration not found: %s", inputFilePath));
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not configure synapse settings", e);
    }
}

From source file:org.apache.syncope.console.commons.XMLRolesReader.java

/**
 * Get all roles allowed for specific page and action requested.
 *
 * @param pageId//from  w  ww  . j  av  a 2  s .c om
 * @param actionId
 * @return roles list comma separated
 */
public String getAllAllowedRoles(final String pageId, final String actionId) {
    if (doc == null) {
        return StringUtils.EMPTY;
    }

    final StringBuilder roles = new StringBuilder();
    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(
                "//page[@id='" + pageId + "']/" + "action[@id='" + actionId + "']/" + "entitlement/text()");
        Object result = expr.evaluate(doc, XPathConstants.NODESET);

        NodeList nodes = (NodeList) result;

        for (int i = 0; i < nodes.getLength(); i++) {
            if (i > 0) {
                roles.append(",");
            }
            roles.append(nodes.item(i).getNodeValue());
        }
    } catch (XPathExpressionException e) {
        LOG.error("While parsing authorizations file", e);
    }

    LOG.debug("Authorizations found: {}", roles);

    return roles.toString();
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
 * Return true if the passed in node or any downstream (higher index)
 * siblings <strong>relative to its destination location</strong> have
 * moveAllowed="false".//from  www.  j ava 2 s  . c o  m
 */
private static boolean isNotReparentable(NodeInfo ni, Element compViewParent, Element positionSet) {

    // This one is easy -- can't re-parent a node with dlm:moveAllowed=false
    if (ni.getNode().getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {
        return true;
    }

    try {
        /*
         *  Annoying to do in Java, but we need to find our own placeholder
         *  element in the positionSet
         */
        final XPathFactory xpathFactory = XPathFactory.newInstance();
        final XPath xpath = xpathFactory.newXPath();
        final String findPlaceholderXpath = ".//*[local-name()='position' and @name='" + ni.getId() + "']";
        final XPathExpression findPlaceholder = xpath.compile(findPlaceholderXpath);
        final NodeList findPlaceholderList = (NodeList) findPlaceholder.evaluate(positionSet,
                XPathConstants.NODESET);
        switch (findPlaceholderList.getLength()) {
        case 0:
            LOG.warn("Node not found for XPathExpression=\"" + findPlaceholderXpath + "\" in positionSet="
                    + XmlUtilitiesImpl.toString(positionSet));
            return true;
        case 1:
            // This is healthy
            break;
        default:
            LOG.warn("More than one node found for XPathExpression=\"" + findPlaceholderXpath
                    + "\" in positionSet=" + XmlUtilitiesImpl.toString(positionSet));
            return true;
        }
        final Element placeholder = (Element) findPlaceholderList.item(0); // At last

        for (Element nextPlaceholder = (Element) placeholder.getNextSibling(); // Start with the next dlm:position element after placeholder
                nextPlaceholder != null; // As long as we have a placeholder to look at
                nextPlaceholder = (Element) nextPlaceholder.getNextSibling()) { // Advance to the next placeholder

            if (LOG.isDebugEnabled()) {
                LOG.debug("Considering whether node ''" + ni.getId()
                        + "' is Reparentable;  subsequent sibling is:  "
                        + nextPlaceholder.getAttribute("name"));
            }

            /*
             * Next task:  we have to find the non-placeholder representation of
             * the nextSiblingPlaceholder within the compViewParent
             */
            final String unmaskPlaceholderXpath = ".//*[@ID='" + nextPlaceholder.getAttribute("name") + "']";
            final XPathExpression unmaskPlaceholder = xpath.compile(unmaskPlaceholderXpath);
            final NodeList unmaskPlaceholderList = (NodeList) unmaskPlaceholder.evaluate(compViewParent,
                    XPathConstants.NODESET);
            switch (unmaskPlaceholderList.getLength()) {
            case 0:
                // Not a problem;  the nextSiblingPlaceholder also refers
                // to a node that has been moved to this context (afaik)
                continue;
            case 1:
                final Element nextSibling = (Element) unmaskPlaceholderList.item(0);
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Considering whether node ''" + ni.getId()
                            + "' is Reparentable;  subsequent sibling '" + nextSibling.getAttribute("ID")
                            + "' has dlm:moveAllowed="
                            + !nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false"));
                }

                // Need to perform some checks...
                if (nextSibling.getAttribute(Constants.ATT_MOVE_ALLOWED).equals("false")) {

                    /*
                     *  The following check is a bit strange;  it seems to verify
                     *  that the current NodeInfo and the nextSibling come from the
                     *  same fragment.  If they don't, the re-parenting is allowable.
                     *  I believe this check could only be unsatisfied in the case
                     *  of tabs.
                     */
                    Precedence p = Precedence.newInstance(nextSibling.getAttribute(Constants.ATT_FRAGMENT));
                    if (ni.getPrecedence().isEqualTo(p)) {
                        return true;
                    }
                }
                break;
            default:
                LOG.warn("More than one node found for XPathExpression=\"" + unmaskPlaceholderXpath
                        + "\" in compViewParent");
                return true;
            }
        }
    } catch (XPathExpressionException xpe) {
        throw new RuntimeException("Failed to evaluate XPATH", xpe);
    }

    return false; // Re-parenting is "not disallowed" (double-negative less readable)

}

From source file:org.apereo.portal.portlets.marketplace.PortletMarketplaceController.java

private List<PortletTab> getPortletTabInfo(DistributedUserLayout layout, String fname) {
    final String XPATH_TAB = "/layout/folder/folder[@hidden = 'false' and @type = 'regular']";
    final String XPATH_COUNT_COLUMNS = "count(./folder[@hidden = \"false\"])";
    final String XPATH_COUNT_NON_EDITABLE_COLUMNS = "count(./folder[@hidden = \"false\" and @*[local-name() = \"editAllowed\"] = \"false\"])";
    final String XPATH_GET_TAB_PORTLET_FMT = ".//channel[@hidden = \"false\" and @fname = \"%s\"]";

    Document doc = layout.getLayout();

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

    try {/* w w w. j  a v a 2 s . c  o  m*/
        XPathExpression tabExpr = xpath.compile(XPATH_TAB);
        NodeList list = (NodeList) tabExpr.evaluate(doc, XPathConstants.NODESET);

        // Count columns and non-editable columns...
        XPathExpression columnCountExpr = xpath.compile(XPATH_COUNT_COLUMNS);
        XPathExpression nonEditableCountExpr = xpath.compile(XPATH_COUNT_NON_EDITABLE_COLUMNS);

        // get the list of tabs...
        String xpathStr = format(XPATH_GET_TAB_PORTLET_FMT, fname);
        XPathExpression portletExpr = xpath.compile(xpathStr);

        List<PortletTab> tabs = new ArrayList<>();
        for (int i = 0; i < list.getLength(); i++) {
            Node tab = list.item(i);
            String tabName = ((Element) tab).getAttribute("name");
            String tabId = ((Element) tab).getAttribute("ID");

            // check if tab is editable...
            Number columns = (Number) columnCountExpr.evaluate(tab, XPathConstants.NUMBER);
            Number nonEditColumns = (Number) nonEditableCountExpr.evaluate(tab, XPathConstants.NUMBER);
            // tab is not editable...  skip it...
            if (columns.intValue() > 0 && columns.intValue() == nonEditColumns.intValue()) {
                continue;
            }

            // get all instances of this portlet on this tab...
            List<String> layoutIds = new ArrayList<>();
            NodeList fnameListPerTab = (NodeList) portletExpr.evaluate(tab, XPathConstants.NODESET);
            for (int j = 0; j < fnameListPerTab.getLength(); j++) {
                Node channel = fnameListPerTab.item(j);

                String layoutId = ((Element) channel).getAttribute("ID");
                layoutIds.add(layoutId);
            }

            PortletTab tabInfo = new PortletTab(tabName, tabId, layoutIds);
            tabs.add(tabInfo);
        }

        return tabs;

    } catch (XPathExpressionException e) {
        logger.error("Error evaluating xpath", e);
    }

    return null;
}

From source file:org.apereo.portal.xml.XmlUtilitiesImplTest.java

@Test
public void testGetUniqueXPath() throws Exception {
    final Document testDoc = loadTestDocument();

    final XPathFactory xPathFactory = XPathFactory.newInstance();
    final XPath xPath = xPathFactory.newXPath();
    final XPathExpression xPathExpression = xPath.compile("//*[@ID='11']");

    final Node node = (Node) xPathExpression.evaluate(testDoc, XPathConstants.NODE);

    final XmlUtilitiesImpl xmlUtilities = new XmlUtilitiesImpl();
    final String nodePath = xmlUtilities.getUniqueXPath(node);

    assertEquals("/layout/folder[2]/folder[3]", nodePath);
}

From source file:org.apereo.portal.xml.xpath.XPathExpressionFactory.java

@Override
public synchronized Object makeObject(Object key) throws Exception {
    final String expression = (String) key;

    final XPath xPath = xPathFactory.newXPath();
    if (this.namespaceContext != null) {
        xPath.setNamespaceContext(this.namespaceContext);
    }/*from   w  w w .  ja v  a 2  s .  c o  m*/
    if (this.variableResolver != null) {
        xPath.setXPathVariableResolver(this.variableResolver);
    }

    logger.debug("Compiling XPathExpression from: {}", expression);

    try {
        return xPath.compile(expression);
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed to compile XPath expression '" + expression + "'", e);
    }
}

From source file:org.artifactory.webapp.wicket.util.DescriptionExtractor.java

private String executeQuery(String query) {
    try {//from   w ww .j ava  2  s  .  c om
        XPathFactory xFactory = XPathFactory.newInstance();
        XPath xpath = xFactory.newXPath();
        xpath.setNamespaceContext(new SchemaNamespaceContext());
        XPathExpression expr = xpath.compile(query);
        Object description = expr.evaluate(doc, XPathConstants.STRING);
        return description.toString().trim();
    } catch (XPathExpressionException e) {
        throw new RuntimeException("Failed to execute xpath query: " + query, e);
    }
}