Example usage for org.apache.commons.jxpath JXPathContext selectNodes

List of usage examples for org.apache.commons.jxpath JXPathContext selectNodes

Introduction

In this page you can find the example usage for org.apache.commons.jxpath JXPathContext selectNodes.

Prototype

public List selectNodes(String xpath) 

Source Link

Document

Finds all nodes that match the specified XPath.

Usage

From source file:de.tudarmstadt.ukp.dkpro.core.tokit.TokenMergerTest.java

@SuppressWarnings("unchecked")
public static List<Object> pick(Collection<?> aContext, String aPath) {
    List<Object> result = new ArrayList<Object>();
    for (Object a : aContext) {
        JXPathContext ctx = JXPathContext.newContext(a);
        ctx.setFunctions(new ClassFunctions(JXPathCasFunctions.class, "cas"));
        result.addAll(ctx.selectNodes(aPath));
    }// ww w  .  j a v a  2  s  .com
    return result;
}

From source file:com.yahoo.xpathproto.ProtoBuilder.java

private static void transformUsingDefinition(final Context vars, final Config config, final JXPathCopier copier,
        final Config.Entry transform) {
    boolean isRepeated = false;
    if (transform.getField() != null) {
        Descriptors.FieldDescriptor fieldDescriptor = copier.getTarget().getDescriptorForType()
                .findFieldByName(transform.getField());
        if (null == fieldDescriptor) {
            throw new RuntimeException("Unknown target field in protobuf: " + transform.getField());
        }//from w  w w .  j a  v  a 2s . c o m

        isRepeated = fieldDescriptor.isRepeated();
    }

    JXPathContext context = copier.getSource();
    if (isRepeated) {
        List list = context.selectNodes(transform.getPath());
        Iterator iterator = list.iterator();
        int limit = 0;
        int count = 0;

        if (transform.getLimit() != null) {
            limit = transform.getLimit();
        }
        logger.debug("Applying limit of {} for field {}", limit, transform.getField());

        while (iterator.hasNext() && (count != limit || limit == 0)) {
            Object value = iterator.next();
            JXPathCopier innerCopier = new JXPathCopier(JXPathContext.newContext(value), copier.getTarget());
            Message.Builder innerBuilder = transformUsing(vars, config, innerCopier, transform.getDefinition());
            if ((transform.getField() != null) && (null != innerBuilder) && (innerBuilder.isInitialized())) {
                copier.copyObject(innerBuilder.build(), transform.getField());
            }
            count++;
        }
    } else {
        JXPathContext innerContext = JXPathCopier.getRelativeContext(context, transform.getPath());
        if (innerContext != null) {
            JXPathCopier innerCopier = new JXPathCopier(innerContext, copier.getTarget());
            Message.Builder innerBuilder = transformUsing(vars, config, innerCopier, transform.getDefinition());
            if ((transform.getField() != null) && (null != innerBuilder) && (innerBuilder.isInitialized())) {
                copier.copyObject(innerBuilder.build(), transform.getField());
            }
        }
    }
}

From source file:de.innovationgate.wga.server.api.Xml.java

/**
 * Executes an XPath expression on some XML text or JavaBean
 * This function always returns lists. If the xpath expression matches only a single values it will return it as single element in a list. If you only want to retrieve single values use xpath().
 * The given object to parse as XML is either a dom4j branch object (mostly document or element), a String containing XML text or a JavaBean. In the last case this function uses JXPath functionality to find a bean property value.
 * This uses the Apache library JXPath under the hood. See their documentation for details how XPath is used to browser JavaBeans.
 * @param object Object to inspect/* w  w  w.jav a 2  s  .  c  o m*/
 * @param xpath XPath expression
 * @param ns Map of namespace prefix declarations used in the XPath. Keys are prefixes, values are namespace URIs.
 * @return Returned value
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
public Object xpathList(Object object, String xpath, Map<String, String> ns)
        throws WGException, DocumentException {
    List<Object> results;
    if (object instanceof String || object instanceof Branch) {
        Branch branch = retrieveBranch(object);
        XPath xpathObj = createXPath(xpath, branch, ns);
        results = xpathObj.selectNodes(branch);
    }

    // Do JXPath on Bean
    else {
        JXPathContext jxContext = JXPathContext.newContext(object);
        jxContext.setLenient(true);
        results = jxContext.selectNodes(xpath);
    }
    return convertXMLObjects(results, true);
}

From source file:com.axelor.data.xml.XMLBinder.java

@SuppressWarnings("unchecked")
private List<Node> find(Node node, XMLBind bind, String prefix) {
    List<Node> nodes = Lists.newArrayList();
    String name = bind.getNode();
    String path = name;/*from   w w w  .  ja  v a2  s  .  c  o  m*/

    if (name == null) {
        return nodes;
    }

    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    if (!("/".equals(prefix))) {
        path = prefix + path;
    }

    try {
        LOG.trace("xpath: " + path);
        JXPathContext context = JXPathContext.newContext(node);
        nodes = context.selectNodes(path);
        LOG.trace("xpath match: " + nodes.size());
    } catch (Exception e) {
        LOG.error("Invalid xpath expression: {}", path);
    }
    return nodes;
}

From source file:com.tunguski.xmlbeans.JXPath.java

/**
 * Select all nodes that are selectable by this XPath
 * expression. If multiple nodes match, multiple nodes
 * will be returned.//  w  w w. j ava2 s.  com
 * <p/>
 * <p/>
 * <b>NOTE:</b> In most cases, nodes will be returned
 * in document-order, as defined by the XML Canonicalization
 * specification.  The exception occurs when using XPath
 * expressions involving the <code>union</code> operator
 * (denoted with the pipe '|' character).
 * </p>
 * <p/>
 * <p/>
 * <b>NOTE:</b> Param node must be a Dom node which will be used during the xpath
 * execution and iteration through the results. A call of node.dispose() must be done
 * after reading all results.
 * </p>
 *
 * @param node The node, nodeset or Context object for evaluation.
 * This value can be null.
 * @return The <code>a list</code> of all items selected
 *         by this XPath expression.
 */
public List selectNodes(Object node) {
    JXPathContext context = JXPathContext.newContext(node);

    // registering namespace prefixes
    for (int i = 0; i < namespaceMap.length; i++) {
        Map.Entry entry = (Map.Entry) namespaceMap[i];
        context.registerNamespace((String) entry.getKey(), (String) entry.getValue());
    }

    List searchResults = context.selectNodes(_queryExpr);
    Iterator searchResultsIter = searchResults.iterator();
    List resultsList = new ArrayList(searchResults.size());
    // id XPath function is returning internal pointers instead of nodes, so
    // we need to filter them
    while (searchResultsIter.hasNext()) {
        Object value = searchResultsIter.next();
        if (value instanceof DOMNodePointer) {
            value = ((DOMNodePointer) value).getNode();
        } else if (value instanceof NullPointer) {
            value = null;
        }

        if (value != null) {
            resultsList.add(value);
        }
    }
    return resultsList;
}

From source file:de.innovationgate.wgpublisher.hdb.HDBModel.java

/**
 * Returns all model definitions for the given content class
 * @param contentClass The content class
 *//*from  w  ww.j  a  v  a 2  s  .  co  m*/
@SuppressWarnings("unchecked")
@CodeCompletion
public List<Content> getModelsForContentClass(String contentClass) {
    JXPathContext jxPath = JXPathContext.newContext(_definition);
    return jxPath.selectNodes("/rootStorages//childContents[@contentClass='" + contentClass + "']");
}

From source file:org.alfresco.web.forms.xforms.Schema2XForms.java

@SuppressWarnings("unchecked")
public static void rebuildInstance(final Node prototypeNode, final Node oldInstanceNode,
        final Node newInstanceNode,

        final HashMap<String, String> schemaNamespaces) {
    final JXPathContext prototypeContext = JXPathContext.newContext(prototypeNode);
    prototypeContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);
    final JXPathContext instanceContext = JXPathContext.newContext(oldInstanceNode);
    instanceContext.registerNamespace(NamespaceService.ALFRESCO_PREFIX, NamespaceService.ALFRESCO_URI);

    for (final String prefix : schemaNamespaces.keySet()) {
        prototypeContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
        instanceContext.registerNamespace(prefix, schemaNamespaces.get(prefix));
    }/*from  w w  w  .  j ava 2 s .  c  o  m*/

    // Evaluate non-recursive XPaths for all prototype elements at this level
    final Iterator<Pointer> it = prototypeContext.iteratePointers("*");
    while (it.hasNext()) {
        final Pointer p = it.next();
        Element proto = (Element) p.getNode();
        String path = p.asPath();
        // check if this is a prototype element with the attribute set
        boolean isPrototype = proto.hasAttributeNS(NamespaceService.ALFRESCO_URI, "prototype")
                && proto.getAttributeNS(NamespaceService.ALFRESCO_URI, "prototype").equals("true");

        // We shouldn't locate a repeatable child with a fixed path
        if (isPrototype) {
            path = path.replaceAll("\\[(\\d+)\\]", "[position() >= $1]");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating prototyped nodes " + path);
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] evaluating child node with positional path " + path);
            }
        }

        Document newInstanceDocument = newInstanceNode.getOwnerDocument();

        // Locate the corresponding nodes in the instance document
        List<Node> l = (List<Node>) instanceContext.selectNodes(path);

        // If the prototype node isn't a prototype element, copy it in as a missing node, complete with all its children. We won't need to recurse on this node
        if (l.isEmpty()) {
            if (!isPrototype) {
                LOGGER.debug("[rebuildInstance] copying in missing node " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));

                // Clone the prototype node and all its children
                Element clone = (Element) proto.cloneNode(true);
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }
            }
        } else {
            // Otherwise, append the matches from the old instance document in order
            for (Node old : l) {
                Element oldEl = (Element) old;

                // Copy the old instance element rather than cloning it, so we don't copy over attributes
                Element clone = null;
                String nSUri = oldEl.getNamespaceURI();
                if (nSUri == null) {
                    clone = newInstanceDocument.createElement(oldEl.getTagName());
                } else {
                    clone = newInstanceDocument.createElementNS(nSUri, oldEl.getTagName());
                }
                newInstanceNode.appendChild(clone);

                if (oldInstanceNode instanceof Document) {
                    // add XMLSchema instance NS
                    addNamespace(clone, NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_NS);
                }

                // Copy over child text if this is not a complex type
                boolean isEmpty = true;
                for (Node n = old.getFirstChild(); n != null; n = n.getNextSibling()) {
                    if (n instanceof Text) {
                        clone.appendChild(newInstanceDocument.importNode(n, false));
                        isEmpty = false;
                    } else if (n instanceof Element) {
                        break;
                    }
                }

                // Populate the nil attribute. It may be true or false
                if (proto.hasAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS, "nil")) {
                    clone.setAttributeNS(NamespaceConstants.XMLSCHEMA_INSTANCE_NS,
                            NamespaceConstants.XMLSCHEMA_INSTANCE_PREFIX + ":nil", String.valueOf(isEmpty));
                }

                // Copy over attributes present in the prototype
                NamedNodeMap attributes = proto.getAttributes();
                for (int i = 0; i < attributes.getLength(); i++) {
                    Attr attribute = (Attr) attributes.item(i);
                    String localName = attribute.getLocalName();
                    if (localName == null) {
                        String name = attribute.getName();
                        if (oldEl.hasAttribute(name)) {
                            clone.setAttributeNode(
                                    (Attr) newInstanceDocument.importNode(oldEl.getAttributeNode(name), false));
                        } else {
                            LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                    + attribute.getNodeName() + " to "
                                    + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                            clone.setAttributeNode((Attr) attribute.cloneNode(false));
                        }
                    } else {
                        String namespace = attribute.getNamespaceURI();
                        if (!((!isEmpty
                                && (namespace.equals(NamespaceConstants.XMLSCHEMA_INSTANCE_NS)
                                        && localName.equals("nil"))
                                || (namespace.equals(NamespaceService.ALFRESCO_URI)
                                        && localName.equals("prototype"))))) {
                            if (oldEl.hasAttributeNS(namespace, localName)) {
                                clone.setAttributeNodeNS((Attr) newInstanceDocument
                                        .importNode(oldEl.getAttributeNodeNS(namespace, localName), false));
                            } else {
                                LOGGER.debug("[rebuildInstance] copying in missing attribute "
                                        + attribute.getNodeName() + " to "
                                        + XMLUtil.buildXPath(clone, newInstanceDocument.getDocumentElement()));

                                clone.setAttributeNodeNS((Attr) attribute.cloneNode(false));
                            }
                        }
                    }
                }

                // recurse on children
                rebuildInstance(proto, oldEl, clone, schemaNamespaces);
            }
        }

        // Now add in a new copy of the prototype
        if (isPrototype) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[rebuildInstance] appending " + proto.getNodeName() + " to "
                        + XMLUtil.buildXPath(newInstanceNode, newInstanceDocument.getDocumentElement()));
            }
            newInstanceNode.appendChild(proto.cloneNode(true));
        }
    }
}

From source file:org.codehaus.mojo.javascript.assembler.JsBuilderAssemblerReader.java

/**
 * {@inheritDoc}/*from  w w  w . j a v a 2s.  c om*/
 * 
 * @see org.codehaus.mojo.javascript.assembler.AssemblerReader#getAssembler(java.io.File)
 */
public Assembler getAssembler(File file) throws Exception {
    logger.info("Reading assembler descriptor " + file.getAbsolutePath());
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document dom = builder.parse(file);

    Assembler assembler = new Assembler();
    JXPathContext xpath = JXPathContext.newContext(dom);
    xpath.setLenient(true);
    String src = (String) xpath.getValue("//directory/@name");
    List nodes = xpath.selectNodes("//target");
    for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
        Node node = (Node) iterator.next();
        Script script = new Script();
        assembler.addScript(script);
        JXPathContext nodeContext = JXPathContext.newContext(node);
        String fileName = (String) nodeContext.getValue("@file");
        fileName = fileName.replace('\\', '/');
        if (fileName.startsWith(OUTPUT)) {
            fileName = fileName.substring(OUTPUT.length());
        }
        script.setFileName(fileName);

        for (Iterator iter = nodeContext.iterate("//include/@name"); iter.hasNext();) {
            String include = ((String) iter.next()).replace('\\', '/');
            if (src != null && src.length() > 0) {
                include = include.substring(src.length() + 1);
            }
            script.addInclude(include);
        }
    }
    return assembler;
}

From source file:org.commonjava.maven.galley.maven.model.view.JXPathContextAncestryTest.java

@Test
@Ignore/*from   www .  ja v a 2 s.co m*/
public void basicJXPathTest() throws Exception {
    final InputStream is = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("jxpath/simple.pom.xml");

    final Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);

    final JXPathContext ctx = JXPathContext.newContext(document);

    document.getDocumentElement().removeAttribute("xmlns");

    final String projectGroupIdPath = "ancestor::project/groupId";

    // NOT what's failing...just populating the node set to traverse in order to feed the ancestor:: axis test.
    final List<?> nodes = ctx.selectNodes("/project/dependencies/dependency");
    for (final Object object : nodes) {
        final Node node = (Node) object;
        dump(node);

        final Stack<Node> revPath = new Stack<Node>();

        Node parent = node;
        while (parent != null) {
            revPath.push(parent);
            parent = parent.getParentNode();
        }

        JXPathContext nodeCtx = null;
        while (!revPath.isEmpty()) {
            final Node part = revPath.pop();
            if (nodeCtx == null) {
                nodeCtx = JXPathContext.newContext(part);
            } else {
                nodeCtx = JXPathContext.newContext(nodeCtx, part);
            }
        }

        System.out
                .println("Path derived from context: '" + nodeCtx.getNamespaceContextPointer().asPath() + "'");

        // brute-force approach...try to force population of the parent pointers by painstakingly constructing contexts for all intermediate nodes.
        System.out.println("Selecting groupId for declaring project using path-derived context...");
        System.out.println(nodeCtx.getValue(projectGroupIdPath));

        // Naive approach...this has all the context info it needs to get parent contexts up to and including the document!
        System.out.println("Selecting groupId for declaring project using non-derived context...");
        System.out.println(JXPathContext.newContext(node).getValue(projectGroupIdPath));
    }
}

From source file:org.commonjava.maven.galley.maven.model.view.MavenXmlView.java

/**
 * Select the ordered list of nodes matching the given XPath expression, rooted in the given context.
 *//*  w w w . ja v  a2 s. c o m*/
protected List<Node> getLocalNodeList(final JXPathContext context, final String path)
        throws GalleyMavenRuntimeException {
    final List<Node> result = new ArrayList<Node>();
    final List<?> iter = context.selectNodes(path);
    if (iter != null) {
        for (final Object obj : iter) {
            result.add((Node) obj);
        }
    }

    return result;
}