Example usage for org.apache.commons.jxpath Pointer asPath

List of usage examples for org.apache.commons.jxpath Pointer asPath

Introduction

In this page you can find the example usage for org.apache.commons.jxpath Pointer asPath.

Prototype

String asPath();

Source Link

Document

Returns a string that is a proper "canonical" XPath that corresponds to this pointer.

Usage

From source file:com.htm.query.jxpath.JXpathQueryEvaluator.java

public List<?> evaluateQuery(IQuery query) throws com.htm.exceptions.IllegalArgumentException {
    log.debug("JXPath: Evaluating XPath query '" + query.getQuery() + "' within context "
            + jXpathContext.getContextBean());
    if (query instanceof XPathQueryImpl) {
        XPathQueryImpl xpath = (XPathQueryImpl) query;
        Hashtable<String, String> namespaces = xpath.getNamespaces();
        if (namespaces != null) {
            for (String key : namespaces.keySet()) {
                this.jXpathContext.registerNamespace(key, namespaces.get(key));
            }/* w w  w.j a v  a2 s .  com*/
        }
    }
    try {
        // TODO if a jdom object is addressed by an xpath expression that is
        // no leaf node
        // then the values of all leaf nodes are returned. This ha to be
        // handled somehow

        // Object result = this.jXpathContext.getValue(query.getQuery());
        //
        // /* Return empty list if xpath query doesn't match any property */
        // if (result == null) {
        // log.debug("JXPath: Query didn't match");
        // return new ArrayList<Object>();
        // } else if (result instanceof List<?>) {
        // log.debug("JXPath: Query matched. Result type "
        // + result.getClass().getName());
        // return (List<?>) result;
        //
        // } else {
        // log.debug("JXPath: Query matched. Result type "
        // + result.getClass().getName());
        // List<Object> resultList = new ArrayList<Object>();
        // resultList.add(result);
        //
        // return resultList;
        // }
        //            if (log.isDebugEnabled()) {
        //                log.debug("Evaluating all paths for query'" + query.getQuery() + "'");
        //                Iterator paths = this.jXpathContext.iteratePointers("/taskParentContext/properties/child::*");
        //                Pointer path;
        //                while (paths.hasNext()) {
        //                    path = (Pointer) paths.next();
        //                    log.debug("Path found: " + path.asPath());
        //                }
        //            }

        ArrayList<Object> list = new ArrayList<Object>();

        Iterator iterator = this.jXpathContext.iteratePointers(query.getQuery());
        Pointer pointer;
        while (iterator.hasNext()) {
            pointer = (Pointer) iterator.next();
            log.debug("JXPath pointer: " + pointer.asPath());
            list.add(pointer.getNode());
        }
        return list;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new InvalidQueryException(e);
    }

}

From source file:jp.terasoluna.fw.beans.JXPathIndexedBeanWrapperImpl.java

/**
 * ???????//from   ww w  .j  av a2 s  .  c  o m
 * @param propertyName ??
 * @return ??????Map??
 */
@Override
public Map<String, Object> getIndexedPropertyValues(String propertyName) {

    // ???Null
    if (StringUtils.isEmpty(propertyName)) {
        String message = "PropertyName is empty!";
        log.error(message);
        throw new IllegalArgumentException(message);
    }

    // ?????
    if (StringUtils.indexOfAny(propertyName, new char[] { '/', '"', '\'' }) != -1) {
        String message = "Invalid character has found within property name." + " '" + propertyName + "' "
                + "Cannot use [ / \" ' ]";
        log.error(message);
        throw new IllegalArgumentException(message);
    }

    // ??[]?[]????
    String stringIndex = extractIndex(propertyName);
    if (stringIndex.length() > 0) {
        try {
            Integer.parseInt(stringIndex);
        } catch (NumberFormatException e) {
            String message = "Invalid character has found within property name." + " '" + propertyName + "' "
                    + "Cannot use [ [] ]";
            log.error(message);
            throw new IllegalArgumentException(message);
        }
    }

    Map<String, Object> result = new LinkedHashMap<String, Object>();
    String requestXpath = toXPath(propertyName);

    // JXPath??
    Iterator<?> ite = null;
    try {
        ite = context.iteratePointers(requestXpath);
    } catch (JXPathException e) {
        // ????
        String message = "Invalid property name. " + "PropertyName: '" + propertyName + "'" + "XPath: '"
                + requestXpath + "'";
        log.error(message, e);
        throw new IllegalArgumentException(message, e);
    }

    // XPath  Java property
    while (ite.hasNext()) {
        Pointer p = (Pointer) ite.next();
        result.put(this.toPropertyName(p.asPath()), p.getValue());
    }
    return result;
}

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  a va  2 s  .  c om

    // 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.RepeaterJXPathBinding.java

/**
 * Uses the mapped identity of each row to detect if rows have been
 * updated, inserted or removed.  Depending on what happened the appropriate
 * child-bindings are allowed to visit the narrowed contexts.
 *///w w  w . j  a  v a  2s  .  c  om
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    // Find the repeater
    Repeater repeater = (Repeater) selectWidget(frmModel, this.repeaterId);
    // and his context, creating the path if needed
    JXPathContext repeaterContext = jxpc.getRelativeContext(jxpc.createPath(this.repeaterPath));

    // create set of updatedRowIds
    Set updatedRows = new HashSet();
    //create list of rows to insert at end
    List rowsToInsert = new ArrayList();

    // iterate rows in the form model...
    int formRowCount = repeater.getSize();
    for (int i = 0; i < formRowCount; i++) {
        Repeater.RepeaterRow thisRow = repeater.getRow(i);

        // Get the identity
        List identity = getIdentity(thisRow);

        if (hasNonNullElements(identity)) {
            // iterate nodes to find match
            Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);
            boolean found = false;
            while (rowPointers.hasNext()) {
                Pointer jxp = (Pointer) rowPointers.next();
                JXPathContext rowContext = repeaterContext.getRelativeContext(jxp);
                List contextIdentity = getIdentity(rowContext);
                if (ListUtils.isEqualList(identity, contextIdentity)) {
                    // match! --> bind to children
                    this.rowBinding.saveFormToModel(thisRow, rowContext);
                    //        --> store rowIdValue in list of updatedRowIds
                    updatedRows.add(identity);
                    found = true;
                    break;
                }
            }
            if (!found) {
                // this is a new row
                rowsToInsert.add(thisRow);
                // also add it to the updated row id's so that this row doesn't get deleted
                updatedRows.add(identity);
            }
        } else {
            // if there is no value to determine the identity --> this is a new row
            rowsToInsert.add(thisRow);
        }
    }
    // Iterate again nodes for deletion
    Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);
    List rowsToDelete = new ArrayList();
    while (rowPointers.hasNext()) {
        Pointer jxp = (Pointer) rowPointers.next();
        JXPathContext rowContext = repeaterContext.getRelativeContext((Pointer) jxp.clone());
        List contextIdentity = getIdentity(rowContext);
        // check if the identity of the rowContext is in the updated rows
        //     if not --> bind for delete
        if (!isIdentityInUpdatedRows(updatedRows, contextIdentity)) {
            rowsToDelete.add(rowContext);
        }
    }
    if (rowsToDelete.size() > 0) {
        // run backwards through the list, so that we don't get into
        // trouble by shifting indexes
        for (int i = rowsToDelete.size() - 1; i >= 0; i--) {
            if (this.deleteRowBinding != null) {
                this.deleteRowBinding.saveFormToModel(frmModel, rowsToDelete.get(i));
            } else {
                // Simply remove the corresponding path
                ((JXPathContext) rowsToDelete.get(i)).removePath(".");
            }
        }
    }
    // count how many we have now
    int indexCount = 1;
    rowPointers = repeaterContext.iteratePointers(this.rowPathForInsert);
    while (rowPointers.hasNext()) {
        rowPointers.next();
        indexCount++;
    }
    // end with rows to insert (to make sure they don't get deleted!)
    if (rowsToInsert.size() > 0) {
        Iterator rowIterator = rowsToInsert.iterator();
        //register the factory!
        while (rowIterator.hasNext()) {
            Repeater.RepeaterRow thisRow = (Repeater.RepeaterRow) rowIterator.next();
            // Perform the insert row binding.
            if (this.insertRowBinding != null) {
                this.insertRowBinding.saveFormToModel(repeater, repeaterContext);
            }
            // -->  create the path to let the context be created
            Pointer newRowContextPointer = repeaterContext
                    .createPath(this.rowPathForInsert + "[" + indexCount + "]");
            JXPathContext newRowContext = repeaterContext.getRelativeContext(newRowContextPointer);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("inserted row at " + newRowContextPointer.asPath());
            }
            //    + rebind to children for update
            this.rowBinding.saveFormToModel(thisRow, newRowContext);
            getLogger().debug("bound new row");
            indexCount++;
        }
        //            } else {
        //                if (getLogger().isWarnEnabled()) {
        //                    getLogger().warn("RepeaterBinding has detected rows to insert, but misses "
        //                            + "the <on-insert-row> binding to do it.");
        //                }
        //            }
    }
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done saving rows " + toString());
    }
}

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

/**
 * Uses the mapped unique-id of each row to detect if rows have been
 * updated, inserted or removed.  Depending on what happened the appropriate
 * child-bindings are alowed to visit the narrowed contexts.
 *//*from w w  w.  j a  va 2 s  .c o m*/
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    // Find the repeater
    Repeater repeater = (Repeater) frmModel.getWidget(this.repeaterId);
    // and his context
    JXPathContext repeaterContext = jxpc.getRelativeContext(jxpc.getPointer(this.repeaterPath));

    // create set of updatedRowIds
    Set updatedRowIds = new HashSet();
    //create list of rows to insert at end
    List rowsToInsert = new ArrayList();

    // iterate rows in the form model...
    int formRowCount = repeater.getSize();
    for (int i = 0; i < formRowCount; i++) {
        Repeater.RepeaterRow thisRow = repeater.getRow(i);

        // Get the key values
        List rowIdValues = getUniqueRowValues(thisRow);

        if (isAnyListElementNotNull(rowIdValues)) {
            // iterate nodes to find match
            Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);
            boolean found = false;
            while (rowPointers.hasNext()) {
                Pointer jxp = (Pointer) rowPointers.next();
                JXPathContext rowContext = repeaterContext.getRelativeContext(jxp);
                List matchIds = getMatchIds(rowContext);
                if (ListUtils.isEqualList(rowIdValues, matchIds)) {
                    // match! --> bind to children
                    this.rowBinding.saveFormToModel(thisRow, rowContext);
                    //        --> store rowIdValue in list of updatedRowIds
                    updatedRowIds.add(rowIdValues);
                    found = true;
                    break;
                }
            }
            if (!found) {
                // this is a new row
                rowsToInsert.add(thisRow);
                // also add it to the updated row id's so that this row doesn't get deleted
                updatedRowIds.add(rowIdValues);
            }
        } else {
            // if all rowIdValues == null --> this is a new row
            rowsToInsert.add(thisRow);
        }
    }
    // Iterate again nodes for deletion
    Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);
    List rowsToDelete = new ArrayList();
    while (rowPointers.hasNext()) {
        Pointer jxp = (Pointer) rowPointers.next();
        JXPathContext rowContext = repeaterContext.getRelativeContext((Pointer) jxp.clone());
        List matchIds = getMatchIds(rowContext);
        // check if matchPath was in list of updates, if not --> bind for delete
        if (!isListInSet(updatedRowIds, matchIds)) {
            rowsToDelete.add(rowContext);
        }
    }
    if (rowsToDelete.size() > 0) {
        if (this.deleteRowBinding != null) {
            // run backwards through the list, so that we don't get into
            // trouble by shifting indexes
            for (int i = rowsToDelete.size() - 1; i >= 0; i--) {
                this.deleteRowBinding.saveFormToModel(frmModel, rowsToDelete.get(i));
            }
        } else {
            if (getLogger().isWarnEnabled()) {
                getLogger().warn("RepeaterBinding has detected rows to delete, "
                        + "but misses the <on-delete-row> binding to do it.");
            }
        }
    }
    // count how many we have now
    int indexCount = 1;
    rowPointers = repeaterContext.iteratePointers(this.rowPathForInsert);
    while (rowPointers.hasNext()) {
        rowPointers.next();
        indexCount++;
    }
    // end with rows to insert (to make sure they don't get deleted!)
    if (rowsToInsert.size() > 0) {
        if (this.insertRowBinding != null) {
            Iterator rowIterator = rowsToInsert.iterator();
            //register the factory!
            while (rowIterator.hasNext()) {
                Repeater.RepeaterRow thisRow = (Repeater.RepeaterRow) rowIterator.next();
                // Perform the insert row binding.
                this.insertRowBinding.saveFormToModel(repeater, repeaterContext);
                // -->  create the path to let the context be created
                Pointer newRowContextPointer = repeaterContext
                        .createPath(this.rowPathForInsert + "[" + indexCount + "]");
                JXPathContext newRowContext = repeaterContext.getRelativeContext(newRowContextPointer);
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("inserted row at " + newRowContextPointer.asPath());
                }
                //    + rebind to children for update
                this.rowBinding.saveFormToModel(thisRow, newRowContext);
                getLogger().debug("bound new row");
                indexCount++;
            }
        } else {
            if (getLogger().isWarnEnabled()) {
                getLogger().warn("RepeaterBinding has detected rows to insert, but misses "
                        + "the <on-insert-row> binding to do it.");
            }
        }
    }
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done saving rows " + toString());
    }
}

From source file:org.chiba.xml.xforms.Bind.java

/**
 * Initializes all bound model items.//  ww  w  .  j av  a 2 s  .com
 *
 * @throws XFormsException if any error occured during model item init.
 */
private void initializeModelItems() throws XFormsException {
    String locationPath = getLocationPath();
    Instance instance = getModel().getInstance(PathUtil.getInstanceId(this.model, locationPath));

    if (instance != null && instance.existsNode(locationPath)) {
        // initialize all bound model items
        Iterator iterator = instance.getPointerIterator(locationPath);
        while (iterator.hasNext()) {
            Pointer instancePointer = (Pointer) iterator.next();
            String path = instancePointer.asPath();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(this + " init: initializing model item for path '" + path + "'");
            }

            // 4.2.1 - 4.b applying model item properties to each node
            initializeModelItemProperties(instance.getModelItem(path));
        }
    }
}

From source file:org.chiba.xml.xforms.constraints.DependencyGraph.java

/**
 * determines which nodes are referenced by given xpath expression and returns them as nodes.
 *
 * @param xpath - the xpath expression under examination
 * @return a list with nodes referenced in given xpath
 *///from  ww w .j  a  v  a 2s .  com
public Vector getXPathRefNodes(JXPathContext relativeContext, String xpath) {
    ReferenceFinder referenceFinder = new ReferenceFinder();
    Parser.parseExpression(xpath, referenceFinder);

    List pathes = referenceFinder.getLocationPathes();
    Vector refNodes = new Vector();

    for (int i = 0; i < pathes.size(); i++) {
        String refPath = pathes.get(i).toString();
        Instance instance = (Instance) relativeContext.getParentContext().getContextBean();
        JXPathContext context = relativeContext;

        if (PathUtil.hasInstanceFunction(refPath)) {
            String instanceId = PathUtil.getInstanceId(instance.getModel(), refPath);

            // use container for instance lookup to allow cross-model references
            instance = (Instance) instance.getModel().getContainer().lookup(instanceId);
            context = instance.getInstanceContext();
        }

        // iterate all referenced nodes
        Iterator iterator = context.iteratePointers(refPath);

        while (iterator.hasNext()) {
            Pointer localPointer = (Pointer) iterator.next();
            //                Object node = localPointer.getNode();
            //                if (node instanceof Pointer) {
            //                    localPointer = (Pointer) node;
            //                }

            String realPath = localPointer.asPath();
            LocalValue localValue = instance.getModelItem(realPath);

            if (localValue != null) {
                // add *existing* reference node
                refNodes.add(localValue.getNode());
            }
        }
    }

    return refNodes;
}

From source file:org.chiba.xml.xforms.constraints.MainDependencyGraph.java

/**
 * builds the dependency graph for a single Bind. Processes all instancenodes that are associated with
 * the bind and creates one Vertex-object for every Modelitem Property found. That means that if there are
 * two instancenodes in the evaluated nodeset, two Vertices for every property (readonly, required, relevant,
 * constraint, calculate) will be created.
 * <p/>/*from   ww  w  . j  a  v a  2 s .  c  o m*/
 * Note: only dynamic Modelitem Properties will be processed.
 */
public void buildBindGraph(Bind bind, Model model) {
    Instance instance;
    String locationPath = bind.getLocationPath();

    instance = model.getInstance(PathUtil.getInstanceId(model, locationPath));

    if (instance == null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("ignoring " + bind);
        }

        // no instance - no dependencies ;-)
        return;
    }

    JXPathContext instanceContext = instance.getInstanceContext();
    Iterator iterator = instance.getPointerIterator(locationPath);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("processing " + bind + " nodeset='" + bind.getBindingExpression() + "'");
        LOGGER.debug("locationPath=" + locationPath);
    }

    while (iterator.hasNext()) {
        Pointer instancePointer = (Pointer) iterator.next();
        JXPathContext relativeContext = instanceContext.getRelativeContext(instancePointer);
        relativeContext.setFunctions(instanceContext.getFunctions());

        String s = instancePointer.asPath();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("processing path:" + s);
        }
        ModelItem modelItem = instance.getModelItem(s);
        NodeImpl node = (NodeImpl) modelItem.getNode();

        if (bind.hasCalculate()) {
            modelItem.setCalculate(bind.getCalculate());
            this.addReferredNodesToGraph(relativeContext, node, bind.getCalculate(), Vertex.CALCULATE_VERTEX);
        }

        if (bind.hasRelevant()) {
            modelItem.setRelevant(bind.getRelevant());
            this.addReferredNodesToGraph(relativeContext, node, bind.getRelevant(), Vertex.RELEVANT_VERTEX);
        }

        if (bind.hasReadonly()) {
            modelItem.setReadonly(bind.getReadonly());
            this.addReferredNodesToGraph(relativeContext, node, bind.getReadonly(), Vertex.READONLY_VERTEX);
        }

        if (bind.hasRequired()) {
            modelItem.setRequired(bind.getRequired());
            this.addReferredNodesToGraph(relativeContext, node, bind.getRequired(), Vertex.REQUIRED_VERTEX);
        }

        if (bind.hasConstraint()) {
            modelItem.setConstraint(bind.getConstraint());
            this.addReferredNodesToGraph(relativeContext, node, bind.getConstraint(), Vertex.CONSTRAINT_VERTEX);
        }

        if (bind.hasDatatype()) {
            modelItem.setDatatype(bind.getDatatype());
        }

        if (bind.hasP3PType()) {
            modelItem.setP3PType(bind.getP3PType());
        }
    }
}

From source file:org.chiba.xml.xforms.constraints.Validator.java

/**
 * Validates the specified instance data node and its descendants.
 *
 * @param instance the instance to be validated.
 * @param path an xpath denoting an arbitrary subtre of the instance.
 * @return <code>true</code> if all relevant instance data nodes are valid
 *         regarding in terms of their <code>constraint</code> and
 *         <code>required</code> properties, otherwise <code>false</code>.
 *///w ww.  ja  v  a 2 s .com
public boolean validate(Instance instance, String path) {
    // initialize
    boolean result = true;
    String expressionPath = path;

    if (!path.endsWith("/")) {
        expressionPath = expressionPath + "/";
    }

    // set expression path to contain the specified path and its subtree
    expressionPath = expressionPath + "descendant-or-self::*";

    // evaluate expression path
    JXPathContext context = instance.getInstanceContext();
    Iterator iterator = context.iteratePointers(expressionPath);
    Pointer locationPointer;
    String locationPath;

    while (iterator.hasNext()) {
        locationPointer = (Pointer) iterator.next();
        locationPath = locationPointer.asPath();
        Element element = (Element) locationPointer.getNode();

        // validate element node against type
        String type = element.getAttributeNS(NamespaceCtx.XMLSCHEMA_INSTANCE_NS, "type");
        result &= validateNode(instance, locationPath, type);

        // handle attributes explicitely since JXPath has
        // seriuos problems with namespaced attributes
        NamedNodeMap attributes = element.getAttributes();

        for (int index = 0; index < attributes.getLength(); index++) {
            Attr attr = (Attr) attributes.item(index);

            if (isInstanceAttribute(attr)) {
                // validate attribute node
                result &= validateNode(instance, locationPath + "/@" + attr.getNodeName());
            }
        }
    }

    return result;
}

From source file:org.chiba.xml.xforms.xpath.test.ExtensionFunctionsTest.java

public void testInstance() throws Exception {
    Document inDocument = getXmlResource("instance-test.xml");

    ChibaBean chibaBean = new ChibaBean();
    chibaBean.setXMLContainer(inDocument);
    chibaBean.init();//from   w  w  w .  ja  va 2  s .  c o m

    //        XPathExtensionFunctions functions = new XPathExtensionFunctions(chibaBean.getContainer().getDefaultModel());
    XPathExtensionFunctions functions = new XPathExtensionFunctions();
    functions.setNamespaceContext(chibaBean.getContainer().getDefaultModel().getDefaultInstance().getElement());

    JXPathContext context = chibaBean.getContainer().getDefaultModel().getDefaultInstance()
            .getInstanceContext();
    context.setFunctions(functions);

    Object o = context.getValue("instance('first')/some-dummy");
    assertTrue(o.equals("some dummy value"));

    o = context.getValue("xforms:instance('first')/some-dummy");
    assertTrue(o.equals("some dummy value"));

    o = context.getValue("instance('second')/.");
    assertTrue(o.equals("another dummy value"));

    Pointer pointer = context.getPointer("instance('second')/.");
    assertEquals("another dummy value", pointer.getValue());
    assertEquals("/another-dummy[1]", pointer.asPath());

    o = context.getValue("xforms:instance('second')/.");
    assertTrue(o.equals("another dummy value"));
}