Example usage for org.dom4j XPath setNamespaceContext

List of usage examples for org.dom4j XPath setNamespaceContext

Introduction

In this page you can find the example usage for org.dom4j XPath setNamespaceContext.

Prototype

void setNamespaceContext(NamespaceContext namespaceContext);

Source Link

Document

Sets the namespace context to be used when evaluating XPath expressions

Usage

From source file:com.collabnet.ccf.core.transformer.DynamicXsltProcessor.java

License:Open Source License

private static XPath buildXpath(Element xslt, final String functionCall) {
    XPath xpath = xslt.createXPath(String.format("//xsl:value-of[@select='%s']", functionCall));
    SimpleNamespaceContext namespaceContext = new SimpleNamespaceContext();
    namespaceContext.addNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
    xpath.setNamespaceContext(namespaceContext);
    return xpath;
}

From source file:com.liferay.alloy.tools.builder.taglib.TagBuilder.java

License:Open Source License

protected Document mergeTlds(Document sourceDoc, Document targetDoc) {
    Element targetRoot = targetDoc.getRootElement();

    DocumentFactory factory = SAXReaderUtil.getDocumentFactory();

    XPath xpathTags = factory.createXPath("//tld:tag");

    Map<String, String> namespaceContextMap = new HashMap<String, String>();

    namespaceContextMap.put(_TLD_XPATH_PREFIX, _TLD_XPATH_URI);

    NamespaceContext namespaceContext = new AlloyGeneratorNamespaceContext(namespaceContextMap);

    xpathTags.setNamespaceContext(namespaceContext);

    List<Node> sources = xpathTags.selectNodes(sourceDoc);

    for (Node source : sources) {
        Element sourceElement = (Element) source;

        String sourceName = sourceElement.elementText("name");

        String xpathTagValue = "//tld:tag[tld:name='" + sourceName + "']";

        XPath xpathTag = factory.createXPath(xpathTagValue);

        xpathTag.setNamespaceContext(namespaceContext);

        List<Node> targets = xpathTag.selectNodes(targetDoc);

        if (targets.size() > 0) {
            Element targetElement = (Element) targets.get(0);

            XPath xpathAttributes = factory.createXPath(xpathTagValue + "//tld:attribute");

            Map<String, String> namespaces = new HashMap<String, String>();

            namespaces.put("tld", StringPool.EMPTY);

            xpathAttributes.setNamespaceURIs(namespaces);

            List<Node> sourceAttributes = xpathAttributes.selectNodes(source);

            for (Node sourceAttribute : sourceAttributes) {
                Element sourceAttributeElement = (Element) sourceAttribute;

                String attributeName = sourceAttributeElement.elementText("name");

                String xpathAttributeValue = "//tld:attribute[tld:name='" + attributeName + "']";

                XPath xpathAttribute = factory.createXPath(xpathTagValue + xpathAttributeValue);

                xpathAttribute.setNamespaceContext(namespaceContext);

                Node targetAttribute = xpathAttribute.selectSingleNode(targetElement);

                if (targetAttribute != null) {
                    targetAttribute.detach();
                }/*from   ww w  .ja  v  a  2  s . c om*/

                targetElement.add(sourceAttributeElement.createCopy());
            }

            Element dynamicAttrElement = targetElement.element("dynamic-attributes");

            if (dynamicAttrElement != null) {
                targetElement.add(dynamicAttrElement.detach());
            }
        } else {
            targetRoot.add(sourceElement.createCopy());
        }
    }

    return targetDoc;
}

From source file:com.surenpi.autotest.suite.parser.XmlSuiteParser.java

License:Apache License

/**
 * ??// w  w  w .jav a 2  s  . c o  m
 * @param suiteInputStream ??
 * @return 
 * @throws DocumentException
 */
public Suite parse(InputStream suiteInputStream) throws DocumentException {
    SAXReader reader = new SAXReader();
    reader.setEncoding("utf-8");

    Document document = reader.read(suiteInputStream);

    simpleNamespaceContext.addNamespace("ns", NS_URI);

    XPath xpath = new DefaultXPath("/ns:suite");
    xpath.setNamespaceContext(simpleNamespaceContext);
    Element suiteEle = (Element) xpath.selectSingleNode(document);
    if (suiteEle == null) {
        suiteEle = document.getRootElement();
        //         throw new RuntimeException("Can not found suite config.");
    }

    Suite suite = new Suite();
    String xmlConfPath = suiteEle.attributeValue("pageConfig");
    String pagePackage = suiteEle.attributeValue("pagePackage", "");
    String rows = suiteEle.attributeValue("rows", "1");
    String lackLines = suiteEle.attributeValue("lackLines", "nearby");
    String errorLines = suiteEle.attributeValue("errorLines", "stop");
    String afterSleep = suiteEle.attributeValue("afterSleep", "0");

    suite.setXmlConfPath(xmlConfPath);
    suite.setPagePackage(pagePackage);
    suite.setRows(rows);
    suite.setLackLines(lackLines);
    suite.setErrorLines(errorLines);
    suite.setAfterSleep(Long.parseLong(afterSleep));

    pagesParse(document, suite);

    return suite;
}

From source file:com.surenpi.autotest.suite.parser.XmlSuiteParser.java

License:Apache License

/**
 * ?page?/*from w  w w .j a v a2s.c  o m*/
 * @param document
 * @param suite
 */
private void pagesParse(Document document, Suite suite) {
    List<SuitePage> pageList = new ArrayList<SuitePage>();
    suite.setPageList(pageList);

    String pagePackage = suite.getPagePackage();
    if (!StringUtils.isBlank(pagePackage)) {
        pagePackage = (pagePackage.trim() + ".");
    }

    XPath xpath = new DefaultXPath("/ns:suite/ns:page");
    xpath.setNamespaceContext(simpleNamespaceContext);

    @SuppressWarnings("unchecked")
    List<Element> pageNodes = xpath.selectNodes(document);
    if (pageNodes == null || pageNodes.size() == 0) {
        throw new RuntimeException("Can not found page config.");
    }

    for (Element pageEle : pageNodes) {
        String pageCls = pageEle.attributeValue("class");

        xpath = new DefaultXPath("ns:actions");
        xpath.setNamespaceContext(simpleNamespaceContext);

        Element actionsEle = (Element) xpath.selectSingleNode(pageEle);
        if (actionsEle == null) {
            throw new RuntimeException("Can not found actions config.");
        }

        String disable = actionsEle.attributeValue("disable", "false");
        if (Boolean.parseBoolean(disable)) {
            continue;
        }

        String beforeSleep = actionsEle.attributeValue("beforeSleep", "0");
        String afterSleep = actionsEle.attributeValue("afterSleep", "0");
        String repeat = actionsEle.attributeValue("repeat", "1");

        List<SuiteAction> actionList = new ArrayList<SuiteAction>();

        SuitePage suitePage = new SuitePage(String.format("%s%s", pagePackage, pageCls));
        suitePage.setActionList(actionList);
        suitePage.setRepeat(Integer.parseInt(repeat));

        pageList.add(suitePage);

        parse(actionList, actionsEle, beforeSleep, afterSleep);
    }
}

From source file:com.vmware.o11n.plugin.powershell.remote.impl.winrm.FaultExtractor.java

License:Open Source License

public XPath getXPath() {
    final XPath xPath = DocumentHelper.createXPath("//" + ns.getPrefix() + ":" + expr);
    xPath.setNamespaceContext(namespaceContext);
    return xPath;
}

From source file:de.tudarmstadt.ukp.dkpro.wsd.io.reader.MASCReader.java

License:Apache License

private XPath createXPath(String xpathExpr) {
    HashMap<String, String> namespaceURIMap = new HashMap<String, String>();
    namespaceURIMap.put("masc", "http://www.xces.org/ns/GrAF/1.0/");

    XPath path = DocumentHelper.createXPath(xpathExpr);
    path.setNamespaceContext(new SimpleNamespaceContext(namespaceURIMap));

    return path;/*from  w  ww  . ja  v a 2  s . c  o  m*/
}

From source file:org.jasig.portlet.widget.links.PortletXmlGroupService.java

License:Apache License

Set<String> getGroups(final String portletName) {
    if (doc == null) {
        return null;
    }// w  w  w  .ja v a 2  s  .  c om
    final String xpathStr = "//p:portlet[p:portlet-name='" + portletName + "']/p:security-role-ref";
    XPath xpath = doc.createXPath(xpathStr);
    xpath.setNamespaceContext(namespaceContext);
    List<Node> roles = xpath.selectNodes(doc);
    if (roles == null || roles.isEmpty()) {
        log.error("No security roles found for portlet: {}", portletName);
        return Collections.emptySet();
    } else {
        Set<String> groups = roles.stream().map(e -> xpathRoleName.selectSingleNode(e).getText())
                .collect(Collectors.toSet());
        return groups;
    }
}

From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluates an XPath expression/*from   w  w w  .j a v a  2s . c  o m*/
 */
public static Object evaluate(final URIResolver uriResolver, Object context,
        final VariableContextImpl variableContext, final DocumentContext documentContext,
        final LocationData locationData, String select, NamespaceContext namespaceContext) {
    FunctionContext functionContext = new FunctionContext() {
        public org.jaxen.Function getFunction(final String namespaceURI, final String prefix,
                final String localName) {

            // Override document() and doc()
            if (/*namespaceURI == null &&*/ ("document".equals(localName) || "doc".equals(localName))) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String url = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            Document result = documentContext.getDocument(url);
                            if (result == null) {
                                Source source = uriResolver.resolve(url, locationData.getSystemID());
                                if (!(source instanceof SAXSource))
                                    throw new ValidationException("Unsupported source type", locationData);
                                XMLReader xmlReader = ((SAXSource) source).getXMLReader();
                                LocationSAXContentHandler contentHandler = new LocationSAXContentHandler();
                                xmlReader.setContentHandler(contentHandler);
                                xmlReader.parse(new InputSource());
                                result = contentHandler.getDocument();
                                documentContext.addDocument(url, result);
                            }
                            return result;
                        } catch (Exception e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "get-namespace-uri-for-prefix".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        String prefix = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                        Element element = null;
                        if (args.get(1) instanceof List) {
                            List list = (List) args.get(1);
                            if (list.size() == 1)
                                element = (Element) list.get(0);
                        } else if (args.get(1) instanceof Element) {
                            element = (Element) args.get(1);
                        }
                        if (element == null)
                            throw new ValidationException("An element is expected as the second argument "
                                    + "in get-namespace-uri-for-prefix()", locationData);
                        return element.getNamespaceForPrefix(prefix);
                    }
                };
            } else if (/*namespaceURI == null &&*/ "distinct-values".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        List originalList = args.get(0) instanceof List ? (List) args.get(0)
                                : Collections.singletonList(args.get(0));
                        List resultList = new ArrayList();
                        XPath stringXPath = Dom4jUtils.createXPath("string(.)");
                        for (Iterator i = originalList.iterator(); i.hasNext();) {
                            Object item = (Object) i.next();
                            String itemString = (String) stringXPath.evaluate(item);
                            if (!resultList.contains(itemString))
                                resultList.add(itemString);
                        }
                        return resultList;
                    }
                };
            } else if (/*namespaceURI == null &&*/ "evaluate".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            if (args.size() != 3) {
                                try {
                                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix,
                                            localName);
                                } catch (UnresolvableException e) {
                                    throw new ValidationException(e, locationData);
                                }
                            } else {
                                String xpathString = (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(args.get(0));
                                XPath xpath = Dom4jUtils.createXPath(xpathString);
                                Map namespaceURIs = new HashMap();
                                List namespaces = (List) args.get(1);
                                for (Iterator i = namespaces.iterator(); i.hasNext();) {
                                    org.dom4j.Namespace namespace = (org.dom4j.Namespace) i.next();
                                    namespaceURIs.put(namespace.getPrefix(), namespace.getURI());
                                }
                                xpath.setNamespaceURIs(namespaceURIs);
                                return xpath.evaluate(args.get(2));
                            }
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "tokenize".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String input = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            List result = new ArrayList();
                            while (input.length() != 0) {
                                int position = input.indexOf(pattern);
                                if (position != -1) {
                                    result.add(input.substring(0, position));
                                    input = input.substring(position + 1);
                                } else {
                                    result.add(input);
                                    input = "";
                                }
                            }
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "string-join".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List strings = (List) args.get(0);
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            StringBuilder result = new StringBuilder();
                            boolean isFirst = true;
                            for (Iterator i = strings.iterator(); i.hasNext();) {
                                if (!isFirst)
                                    result.append(pattern);
                                else
                                    isFirst = false;
                                String item = (String) (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(i.next());
                                result.append(item);
                            }
                            return result.toString();
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "reverse".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List result = new ArrayList((List) args.get(0));
                            Collections.reverse(result);
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else {
                try {
                    // Go through standard XPath functions
                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName);
                } catch (UnresolvableException e) {
                    // User-defined function
                    try {
                        final Closure closure = findClosure(
                                variableContext.getVariableValue(namespaceURI, prefix, localName));
                        if (closure == null)
                            throw new ValidationException(
                                    "'" + qualifiedName(prefix, localName) + "' is not a function",
                                    locationData);
                        return new org.jaxen.Function() {
                            public Object call(Context context, List args) {
                                return closure.execute(args);
                            }
                        };
                    } catch (UnresolvableException e2) {
                        throw new ValidationException("Cannot invoke function '"
                                + qualifiedName(prefix, localName) + "', no such function", locationData);
                    }
                }
            }
        }

        private Closure findClosure(Object xpathObject) {
            if (xpathObject instanceof Closure) {
                return (Closure) xpathObject;
            } else if (xpathObject instanceof List) {
                for (Iterator i = ((List) xpathObject).iterator(); i.hasNext();) {
                    Closure closure = findClosure(i.next());
                    if (closure != null)
                        return closure;
                }
                return null;
            } else {
                return null;
            }
        }
    };

    try {
        // Create XPath
        XPath xpath = Dom4jUtils.createXPath(select);

        // Set variable, namespace, and function context
        if (context instanceof Context) {
            // Create a new context, as Jaxen may modify the current node in the context (is this a bug?)
            Context currentContext = (Context) context;
            Context newContext = new Context(new ContextSupport(namespaceContext, functionContext,
                    variableContext, DocumentNavigator.getInstance()));
            newContext.setNodeSet(currentContext.getNodeSet());
            newContext.setSize(currentContext.getSize());
            newContext.setPosition(currentContext.getPosition());
            context = newContext;
        } else {
            xpath.setVariableContext(variableContext);
            xpath.setNamespaceContext(namespaceContext);
            xpath.setFunctionContext(functionContext);
        }

        // Execute XPath
        return xpath.evaluate(context);
    } catch (Exception e) {
        throw new ValidationException(e, locationData);
    }
}

From source file:org.orbeon.oxf.xml.XPathUtils.java

License:Open Source License

/**
 * Apply the given XPath expression to the given node.
 *
 * @param   prefixes  mapping of prefixes to namespace URIs for prefixes used in expr
 * @return            Iterator over org.w3c.dom.Node objects, never null
 *//*ww  w. ja va  2s.c om*/
public static Iterator selectIterator(org.dom4j.Node node, String expr, Map prefixes) {
    try {
        org.dom4j.XPath path = node.createXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));

        return new IteratorFilter(path.selectNodes(node).iterator(), org.dom4j.Namespace.class);
    } catch (InvalidXPathException e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.xml.XPathUtils.java

License:Open Source License

/**
 * Apply the given XPath expression to the given node.
 *
 * @param prefixes  mapping of prefixes to namespace URIs for prefixes used in expr
 *//*w w  w.  j  av  a 2  s  .  c om*/
public static Node selectSingleNode(Node node, String expr, Map prefixes) {
    try {
        XPath path = new DOMXPath(expr);
        path.setNamespaceContext(new SimpleNamespaceContext(prefixes));
        return (Node) path.selectSingleNode(node);
    } catch (JaxenException e) {
        throw new OXFException(e);
    }
}