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

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

Introduction

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

Prototype

public abstract Iterator iteratePointers(String xpath);

Source Link

Document

Traverses the xpath and returns an Iterator of Pointers.

Usage

From source file:blueprint.sdk.util.JXPathHelper.java

/**
 * @param xpath XPath to evaluate/*from  ww  w .ja va  2s . c o m*/
 * @param context target context, JXPathContext.newContext(Node)
 * @return Iterator or null(not found)
 */
@SuppressWarnings("unchecked")
public static Iterator<Pointer> evaluateIteratorPointers(String xpath, JXPathContext context) {
    Iterator<Pointer> result = null;

    try {
        result = context.iteratePointers(xpath);
    } catch (JXPathNotFoundException ignored) {
    }

    return result;
}

From source file:net.sf.ahtutils.report.jxpath.TestDataTypesJXpath.java

@Test
public void test() {
    TestDataStructure structure = new TestDataStructure();
    //structure.setIntegerValue(1);
    //structure.setLongValue(2);

    JXPathContext context = JXPathContext.newContext(structure);
    String queryInteger = "@integerValue";
    String queryLong = "@longValue";

    Iterator iteratorLong = context.iteratePointers(queryLong);
    while (iteratorLong.hasNext()) {
        Pointer pointerToItem = (Pointer) iteratorLong.next();
        System.out.println("Got pointer: " + pointerToItem.getValue().getClass() + " with value = "
                + pointerToItem.getValue().toString());
    }/*from w w  w . j a  v  a 2s. c  o m*/

    Iterator iteratorInteger = context.iteratePointers(queryInteger);
    while (iteratorInteger.hasNext()) {
        Pointer pointerToItem = (Pointer) iteratorInteger.next();
        System.out.println("Got pointer: " + pointerToItem.getValue().getClass() + " with value = "
                + pointerToItem.getValue().toString());
    }

}

From source file:jp.go.nict.langrid.bpel.ProcessAnalyzer.java

/**
 * /*from   w  w w.j a  va 2 s . co m*/
 * 
 */
public static WSDL analyzeWsdl(byte[] body) throws MalformedURLException, SAXException, URISyntaxException {
    JXPathContext context = JXPathContext.newContext(new DOMParser().parseXML(new ByteArrayInputStream(body)));
    context.registerNamespace("_", Constants.WSDL_URI);
    context.registerNamespace("wsdlsoap", Constants.WSDLSOAP_URI);
    context.registerNamespace("plnk1", Constants.PLNK_URI);
    context.registerNamespace("plnk2", Constants.PLNK_URI_2);

    WSDL wsdl = new WSDL();
    wsdl.setBody(body);
    wsdl.setTargetNamespace(new URI(context.getValue("/_:definitions/@targetNamespace").toString()));

    // 
    // 
    HashMap<String, PartnerLinkType> links = new HashMap<String, PartnerLinkType>();
    {
        Iterator<?> pli = context.iteratePointers("/_:definitions/plnk1:partnerLinkType");
        while (pli.hasNext()) {
            JXPathContext pltc = JXPathContext.newContext(context, ((Pointer) pli.next()).getNode());
            pltc.registerNamespace("plnk1", Constants.PLNK_URI);
            PartnerLinkType plt = new PartnerLinkType();
            plt.setName(pltc.getValue("/@name").toString());

            HashMap<String, Role> roles = new HashMap<String, Role>();
            Iterator<?> ri = pltc.iteratePointers("/plnk1:role");
            while (ri.hasNext()) {
                JXPathContext rc = JXPathContext.newContext(pltc, ((Pointer) ri.next()).getNode());
                rc.registerNamespace("plnk1", Constants.PLNK_URI);
                Role role = new Role();
                role.setName(rc.getValue("/@name").toString());
                role.setPortType(toQName(rc, rc.getValue("/plnk1:portType/@name").toString()));
                roles.put(role.getName(), role);
            }
            plt.setRoles(roles);
            links.put(plt.getName(), plt);
        }
    }
    {
        Iterator<?> pli = context.iteratePointers("/_:definitions/plnk2:partnerLinkType");
        while (pli.hasNext()) {
            JXPathContext pltc = JXPathContext.newContext(context, ((Pointer) pli.next()).getNode());
            pltc.registerNamespace("plnk2", Constants.PLNK_URI_2);
            PartnerLinkType plt = new PartnerLinkType();
            plt.setName(pltc.getValue("/@name").toString());

            HashMap<String, Role> roles = new HashMap<String, Role>();
            Iterator<?> ri = pltc.iteratePointers("/plnk2:role");
            while (ri.hasNext()) {
                JXPathContext rc = JXPathContext.newContext(pltc, ((Pointer) ri.next()).getNode());
                Role role = new Role();
                role.setName(rc.getValue("/@name").toString());
                role.setPortType(toQName(rc, rc.getValue("/@portType").toString()));
                roles.put(role.getName(), role);
            }
            plt.setRoles(roles);
            links.put(plt.getName(), plt);
        }
    }
    wsdl.setPlinks(links);

    { // definitions/portType??
        HashMap<String, EndpointReference> portTypeToEndpointReference = new HashMap<String, EndpointReference>();
        Iterator<?> pti = context.iteratePointers("/_:definitions/_:portType");
        while (pti.hasNext()) {
            JXPathContext ptc = JXPathContext.newContext(context, ((Pointer) pti.next()).getNode());
            portTypeToEndpointReference.put(ptc.getValue("/@name").toString(), null);
        }
        wsdl.setPortTypeToEndpointReference(portTypeToEndpointReference);
    }

    { // definitions/binding??
        HashMap<String, QName> bindingTypes = new HashMap<String, QName>();
        Iterator<?> bi = context.iteratePointers("/_:definitions/_:binding");
        while (bi.hasNext()) {
            JXPathContext bc = JXPathContext.newContext(context, ((Pointer) bi.next()).getNode());
            bindingTypes.put(bc.getValue("/@name").toString(), toQName(bc, bc.getValue("/@type").toString()));
        }
        wsdl.setBindingTypes(bindingTypes);
    }

    String firstServiceName = null;
    { // definitions/service??
        HashMap<String, Service> services = new HashMap<String, Service>();
        Iterator<?> si = context.iteratePointers("/_:definitions/_:service");
        while (si.hasNext()) {
            JXPathContext sc = JXPathContext.newContext(context, ((Pointer) si.next()).getNode());
            sc.registerNamespace("_", Constants.WSDL_URI);
            String serviceName = sc.getValue("/@name").toString();

            Service s = new Service();
            s.setName(serviceName);
            if (firstServiceName == null) {
                firstServiceName = serviceName;
            }

            // port??
            HashMap<String, Port> ports = new HashMap<String, Port>();
            Iterator<?> pi = sc.iteratePointers("/_:port");
            while (pi.hasNext()) {
                JXPathContext pc = JXPathContext.newContext(sc, ((Pointer) pi.next()).getNode());
                pc.registerNamespace("wsdlsoap", Constants.WSDLSOAP_URI);
                Port p = new Port();
                p.setName(pc.getValue("/@name").toString());
                p.setBinding(toQName(pc, pc.getValue("/@binding").toString()));
                p.setAddress(new URL(pc.getValue("/wsdlsoap:address/@location").toString()));
                ports.put(p.getName(), p);
            }
            s.setPorts(ports);

            services.put(s.getName(), s);
        }
        wsdl.setServices(services);
    }

    if (firstServiceName == null) {
        wsdl.setFilename("unknown" + WSDL_EXTENSION);
    } else {
        wsdl.setFilename(firstServiceName + WSDL_EXTENSION);
    }
    return wsdl;
}

From source file:com.opera.core.systems.scope.AbstractService.java

/**
 * Query a collection JXPath and return a pointer FIXME: This does not belong
 * here!/*from  w ww.  j  a  va2s  .co  m*/
 *
 * @param collection
 * @param query
 * @return Pointer to node
 */
public Iterator<?> xpathIterator(Collection<?> collection, String query) {
    JXPathContext pathContext = JXPathContext.newContext(collection);
    Iterator<?> result = null;
    try {
        result = pathContext.iteratePointers(query);
    } catch (JXPathNotFoundException e) {
        logger.log(Level.WARNING, "JXPath exception: {0}", e.getMessage());
    }
    return result;
}

From source file:com.idega.util.config.DefaultConfig.java

/**
 * Creates and loads a new configuration.
 * //from   w w  w.  j  a v  a  2s .  c  o  m
 * @param stream
 *            InputStream to read XML data in the default format.
 */
public DefaultConfig(InputStream stream) throws ConfigException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);

        Document document = factory.newDocumentBuilder().parse(stream);
        JXPathContext context = JXPathContext.newContext(document.getDocumentElement());

        for (Iterator iter = context.iteratePointers(properties_xpath); iter.hasNext();) {
            Pointer pointer = (Pointer) iter.next();
            Element properties_el = (Element) pointer.getNode();
            String p_name = properties_el.getAttribute(name_att);

            JXPathContext properties_context = JXPathContext.newContext(properties_el);
            Map<String, String> properties = load(properties_context, property_xpath, name_att, value_att);
            getPropertiesMap().put(p_name, properties);
        }

    } catch (Exception e) {
        throw new ConfigException(e);
    }
}

From source file:com.idega.util.config.DefaultConfig.java

/**
 * Returns the specified configuration section in a hash map.
 * /* w  w  w  .ja  v  a 2 s. c om*/
 * @param configContext
 *            the JXPath context holding the configuration.
 * @param sectionPath
 *            the context relative path to the section.
 * @param nameAttribute
 *            the name of the attribute to be used as a hash map key.
 * @param valueAttribute
 *            the name of the attribute to be used as a hash map value.
 * @return the specified configuration section in a hash map.
 * @throws Exception
 *             if any error occured during configuration loading.
 */
private HashMap load(JXPathContext configContext, String sectionPath, String nameAttribute,
        String valueAttribute) throws Exception {
    HashMap map = new HashMap();
    Iterator iterator = configContext.iteratePointers(sectionPath);

    while (iterator.hasNext()) {
        Pointer pointer = (Pointer) iterator.next();
        Element element = (Element) pointer.getNode();

        map.put(element.getAttribute(nameAttribute), element.getAttribute(valueAttribute));
    }

    return map;
}

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));
    }// w w  w .  ja v  a 2  s . co 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.apache.cocoon.forms.binding.EnhancedRepeaterJXPathBinding.java

public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Repeater repeater = (Repeater) selectWidget(frmModel, super.getId());
    if (!(repeater instanceof EnhancedRepeater)) {
        super.doSave(frmModel, jxpc);
        return;// w ww.j a v  a2 s  . c om
    }

    EnhancedRepeater rep = (EnhancedRepeater) repeater;
    rep.doPageSave();
    Pointer ptr = jxpc.getPointer(super.getRepeaterPath());
    JXPathContext repeaterContext = jxpc.getRelativeContext(ptr);
    RepeaterJXPathCollection collection = rep.getCollection();
    // iterate updated rows. note: we don't iterate over the whole context
    for (Iterator iter = collection.getUpdatedRows().iterator(); iter.hasNext();) {
        RepeaterItem item = (RepeaterItem) iter.next();
        Repeater.RepeaterRow thisRow = item.getRow();
        // Get the identity
        List identity = getIdentity(thisRow);
        if (hasNonNullElements(identity)) {
            // iterate nodes to find match
            Iterator rowPointers = repeaterContext.iteratePointers(getRowPath());
            while (rowPointers.hasNext()) {
                Pointer jxp = (Pointer) rowPointers.next();
                JXPathContext rowContext = repeaterContext.getRelativeContext(jxp);
                List contextIdentity = getIdentity(rowContext);
                if (ListUtils.isEqualList(identity, contextIdentity)) {
                    getRowBinding().saveFormToModel(thisRow, rowContext);
                    break;
                }
            }
        } else {
            getRowBinding().saveFormToModel(thisRow, item.getContext().getContextPointer());
        }
    }

    for (Iterator iter = collection.getDeletedRows().iterator(); iter.hasNext();) {
        RepeaterItem item = (RepeaterItem) iter.next();
        jxpc.removePath(item.getContext().createPath(".").asPath());
    }

    // insert rows
    int indexCount = collection.getOriginalCollectionSize() - collection.getDeletedRows().size();
    for (Iterator iter = collection.getInsertedRows().iterator(); iter.hasNext();) {
        indexCount++;
        RepeaterItem item = (RepeaterItem) iter.next();

        // Perform the insert row binding.
        if (getInsertRowBinding() != null) {
            getInsertRowBinding().saveFormToModel(item.getRow(), repeaterContext);
        }
        // -->  create the path to let the context be created
        Pointer newRowContextPointer = repeaterContext
                .createPath(super.getInsertRowPath() + "[" + indexCount + "]");
        JXPathContext newRowContext = repeaterContext.getRelativeContext(newRowContextPointer);
        //    + rebind to children for update
        super.getRowBinding().saveFormToModel(item.getRow(), newRowContext);
    }
}

From source file:org.apache.cocoon.forms.binding.MultiValueJXPathBinding.java

public void doSave(Widget frmModel, JXPathContext jctx) throws BindingException {
    Widget widget = selectWidget(frmModel, this.multiValueId);
    Object[] values = (Object[]) widget.getValue();

    JXPathContext multiValueContext = jctx.getRelativeContext(jctx.createPath(this.multiValuePath));

    // Delete all that is already present

    // Unfortunately the following statement doesn't work (it doesn't removes all elements from the 
    // list because of a bug in JXPath I wasn't able to locate).
    //multiValueContext.removeAll(this.rowPath);

    // TODO: This is a workaround until the bug in commons-jxpath is found, fixed and released
    Iterator rowPointers = multiValueContext.iteratePointers(this.rowPath);
    int cnt = 0;/* www .  ja va 2s .c o  m*/
    while (rowPointers.hasNext()) {
        cnt++;
        rowPointers.next();
    }
    while (cnt >= 1) {
        String thePath = this.rowPath + "[" + cnt + "]";
        multiValueContext.removePath(thePath);
        cnt--;
    }

    boolean update = false;

    if (values != null) {
        // first update the values
        for (int i = 0; i < values.length; i++) {
            String path = this.rowPath + '[' + (i + 1) + ']';
            Pointer rowPtr = multiValueContext.createPath(path);

            Object value = values[i];
            if (value != null && convertor != null) {
                value = convertor.convertToString(value, convertorLocale, null);
            }

            rowPtr.setValue(value);
        }

        // now perform any other bindings that need to be performed when the value is updated
        this.updateBinding.saveFormToModel(frmModel, multiValueContext);

        update = true;
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done saving " + toString() + " -- on-update == " + update);
    }

}

From source file:org.apache.cocoon.forms.binding.RepeaterJXPathBinding.java

/**
 * Binds the unique-id of the repeated rows, and narrows the context on
 * objectModelContext and Repeater to the repeated rows before handing
 * over to the actual binding-children.//from w  w  w  .  j  a  va  2 s .c  om
 */
public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException {
    // Find the repeater
    Repeater repeater = (Repeater) selectWidget(frmModel, this.repeaterId);
    if (repeater == null) {
        throw new BindingException("The repeater with the ID [" + this.repeaterId
                + "] referenced in the binding does not exist in the form definition.");
    }
    repeater.clear();

    Pointer ptr = jxpc.getPointer(this.repeaterPath);
    if (ptr.getNode() != null) {
        // There are some nodes to load from

        int initialSize = repeater.getSize();

        // build a jxpath iterator for pointers
        JXPathContext repeaterContext = jxpc.getRelativeContext(ptr);
        Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);
        //iterate through it
        while (rowPointers.hasNext()) {
            // create a new row, take that as the frmModelSubContext
            Repeater.RepeaterRow thisRow;
            if (initialSize > 0) {
                thisRow = repeater.getRow(--initialSize);
            } else {
                thisRow = repeater.addRow();
            }
            // make a jxpath ObjectModelSubcontext on the iterated element
            Pointer jxp = (Pointer) rowPointers.next();
            JXPathContext rowContext = repeaterContext.getRelativeContext(jxp);
            // hand it over to children
            if (this.identityBinding != null) {
                this.identityBinding.loadFormFromModel(thisRow, rowContext);
            }
            this.rowBinding.loadFormFromModel(thisRow, rowContext);
        }
    }
    if (getLogger().isDebugEnabled())
        getLogger().debug("done loading rows " + toString());
}