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

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

Introduction

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

Prototype

public abstract JXPathContext getRelativeContext(Pointer pointer);

Source Link

Document

Returns a JXPathContext that is relative to the current JXPathContext.

Usage

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

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *//*www  .  ja  va2s .  c  o  m*/
public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Struct structWidget = (Struct) getWidget(frmModel, this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    super.doLoad(structWidget, subContext);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done loading " + toString());
    }
}

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

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *//*from   www.  j a v a2  s.  co  m*/
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Struct structWidget = (Struct) frmModel.getWidget(this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    super.doSave(structWidget, subContext);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done saving " + toString());
    }
}

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

public void doLoad(Widget frmModel, JXPathContext jctx) throws BindingException {
    // (There should be a general widget type checker for all the bindings to use,
    // coupled with a general informative exception class to throw if the widget is
    // of the wrong type or null.)
    Repeater repeater = (Repeater) frmModel.getWidget(this.repeaterId);
    if (repeater == null) {
        String fullId = frmModel.getFullyQualifiedId();
        if (fullId == null || fullId.length() == 0) {
            fullId = "";
        } else {/* ww  w  . j av  a  2  s  . c  o  m*/
            fullId = fullId + ".";
        }
        throw new RuntimeException("TempRepeaterJXPathBinding: Repeater \"" + fullId + this.repeaterId
                + "\" does not exist (" + frmModel.getLocation() + ")");
    }

    // Start by clearing the repeater, if necessary.
    if (this.clearOnLoad) {
        repeater.removeRows();
    }

    // Find the location of the repeater data.
    Pointer repeaterPointer = jctx.getPointer(this.repeaterPath);

    // Check if there is data present.
    //
    // (Otherwise, should we check the leniency config option
    // to decide whether to be silent or throw an exception?) 
    if (repeaterPointer != null) {

        // Narrow to repeater context.
        JXPathContext repeaterContext = jctx.getRelativeContext(repeaterPointer);

        // Build a jxpath iterator for the repeater row pointers.
        Iterator rowPointers = repeaterContext.iteratePointers(this.rowPath);

        // Iterate through the rows of data.
        int rowNum = 0;
        while (rowPointers.hasNext()) {

            // Get or create a row widget.
            Repeater.RepeaterRow thisRow;
            if (repeater.getSize() > rowNum) {
                thisRow = repeater.getRow(rowNum);
            } else {
                thisRow = repeater.addRow();
            }
            rowNum++;

            // Narrow to the row context.
            Pointer rowPointer = (Pointer) rowPointers.next();
            JXPathContext rowContext = repeaterContext.getRelativeContext(rowPointer);

            // If virtual rows are requested, place a deep clone of the row data
            // into a temporary node, and narrow the context to this virtual row.
            //
            // (A clone of the data is used to prevent modifying the source document.
            // Otherwise, the appendChild method would remove the data from the source
            // document.  Is this protection worth the penalty of a deep clone?)
            //
            // (This implementation of virtual rows currently only supports DOM
            // bindings, but could easily be extended to support other bindings.)

            if (virtualRows == true) {
                Node repeaterNode = (Node) repeaterPointer.getNode();
                Node virtualNode = repeaterNode.getOwnerDocument().createElementNS(null, "virtual");
                Node clone = ((Node) rowPointer.getNode()).cloneNode(true);
                virtualNode.appendChild(clone);
                rowContext = JXPathContext.newContext(repeaterContext, virtualNode);
            }

            // Finally, perform the load row binding.
            this.rowBinding.loadFormFromModel(thisRow, rowContext);
        }
    }

    if (getLogger().isDebugEnabled())
        getLogger().debug("done loading rows " + toString());
}

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

public void doSave(Widget frmModel, JXPathContext jctx) throws BindingException {
    // (See comment in doLoad about type checking and throwing a meaningful exception.)
    Repeater repeater = (Repeater) frmModel.getWidget(this.repeaterId);

    // Perform shortcut binding if the repeater is empty
    // and the deleteIfEmpty config option is selected.
    if (repeater.getSize() == 0 && this.deleteIfEmpty) {
        // Delete all of the old data for this repeater.
        jctx.removeAll(this.repeaterPath);

        // Otherwise perform the normal save binding.
    } else {/*from  www  .j  a  v a  2 s  .c  o  m*/

        // Narrow to the repeater context, creating the path if it did not exist.
        JXPathContext repeaterContext = jctx.getRelativeContext(jctx.createPath(this.repeaterPath));

        // Start by deleting all of the old row data.
        repeaterContext.removeAll(this.rowPath);

        // Verify that repeater is not empty and has an insert row binding.
        if (repeater.getSize() > 0) {
            if (this.insertRowBinding != null) {

                //register the factory!
                //this.insertRowBinding.saveFormToModel(repeater, repeaterContext);

                // Iterate through the repeater rows.
                for (int i = 0; i < repeater.getSize(); i++) {

                    // Narrow to the repeater row context.
                    Pointer rowPointer = repeaterContext.getPointer(this.rowPathInsert);
                    JXPathContext rowContext = repeaterContext.getRelativeContext(rowPointer);

                    // Variables used for virtual rows.
                    // They are initialized here just to keep the compiler happy. 
                    Node rowNode = null;
                    Node virtualNode = null;

                    // If virtual rows are requested, create a temporary node and
                    // narrow the context to this initially empty new virtual row.
                    if (virtualRows == true) {
                        rowNode = (Node) rowContext.getContextBean();
                        virtualNode = rowNode.getOwnerDocument().createElementNS(null, "virtual");
                        rowContext = JXPathContext.newContext(repeaterContext, virtualNode);
                    }

                    // Perform the insert row binding
                    this.insertRowBinding.saveFormToModel(repeater, rowContext);

                    // Perform the save row binding.
                    this.rowBinding.saveFormToModel(repeater.getRow(i), rowContext);

                    // If virtual rows are requested, finish by appending the
                    // children of the virtual row to the real context node.
                    if (virtualRows == true) {
                        NodeList list = virtualNode.getChildNodes();
                        int count = list.getLength();
                        for (int j = 0; j < count; j++) {
                            // The list shrinks when a child is appended to the context
                            // node, so we always reference the first child in the list.
                            rowNode.appendChild(list.item(0));
                        }
                    }
                    getLogger().debug("bound new row");
                }
            } else {
                getLogger().warn("TempRepeaterBinding has detected rows to insert, "
                        + "but misses the <on-insert-row> binding to do it.");
            }
        }
    }
}

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

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *//*from   ww  w.j a  v a2 s .com*/
public void doLoad(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Widget widget = frmModel.getWidget(this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    if (!(widget instanceof Union))
        throw new RuntimeException(
                "Binding: Expected Union widget, but received class: \"" + widget.getClass().getName() + "\".");
    Union unionWidget = (Union) widget;
    Binding[] subBindings = getChildBindings();
    if (subBindings != null) {
        int size = subBindings.length;
        for (int i = 0; i < size; i++) {
            subBindings[i].loadFormFromModel(unionWidget, subContext);
        }
    }
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done loading " + toString());
    }
}

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

/**
 * Narrows the scope on the form-model to the member widget-field, and
 * narrows the scope on the object-model to the member xpath-context
 * before continuing the binding over the child-bindings.
 *//*from www  .  j a va 2 s  .c om*/
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Union unionWidget = (Union) frmModel.getWidget(this.widgetId);
    JXPathContext subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
    Binding[] subBindings = getChildBindings();
    if (subBindings != null) {
        int size = subBindings.length;
        for (int i = 0; i < size; i++) {
            subBindings[i].saveFormToModel(unionWidget, subContext);
        }
    }
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("done saving " + toString());
    }
}

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

/**
 * Actively performs the binding from the Woody-form to the ObjectModel
 * wrapped in a jxpath context//  ww  w.  j  a  v a  2 s  .c  o m
 */
public void doSave(Widget frmModel, JXPathContext jxpc) throws BindingException {
    Widget widget = frmModel.getWidget(this.fieldId);
    Object value = widget.getValue();
    if (value != null && convertor != null) {
        value = convertor.convertToString(value, convertorLocale, null);
    }

    Object oldValue = jxpc.getValue(this.xpath);
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("value= " + value + "-- oldvalue=" + oldValue);
    }

    boolean update = false;

    if ((value == null && oldValue != null) || value != null && !value.equals(oldValue)) {
        // first update the value itself
        jxpc.createPathAndSetValue(this.xpath, value);

        // now perform any other bindings that need to be performed when the value is updated
        JXPathContext subContext = null;
        try {
            subContext = jxpc.getRelativeContext(jxpc.getPointer(this.xpath));
        } catch (JXPathException e) {
            // if the value has been set to null and the underlying model is a bean, then
            // JXPath will not be able to create a relative context
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("(Ignorable) problem binding field " + widget.getFullyQualifiedId(), e);
            }
        }
        if (subContext != null) {
            this.updateBinding.saveFormToModel(frmModel, subContext);
        }

        update = true;
    }

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

From source file:org.apache.cocoon.woody.datatype.FlowJXPathSelectionList.java

public void generateSaxFragment(ContentHandler contentHandler, Locale locale) throws SAXException {
    JXPathContext ctx = null;
    Iterator iter = null;/*from   w w w .  j  a  v a 2  s  .c om*/
    if (model == null) {
        Object flowData = FlowHelper.getContextObject(ContextHelper.getObjectModel(this.context));
        if (flowData == null) {
            throw new SAXException("No flow data to produce selection list");
        }

        // Move to the list location
        ctx = JXPathContext.newContext(flowData);

        // Iterate on all elements of the list
        iter = ctx.iteratePointers(this.listPath);
    } else {
        // Move to the list location
        ctx = JXPathContext.newContext(model);

        // Iterate on all elements of the list
        iter = ctx.iteratePointers(".");
    }

    // Start the selection-list
    contentHandler.startElement(Constants.WI_NS, SELECTION_LIST_EL,
            Constants.WI_PREFIX_COLON + SELECTION_LIST_EL, Constants.EMPTY_ATTRS);

    while (iter.hasNext()) {
        String stringValue = "";
        Object label = null;

        // Get a context on the current item
        Pointer ptr = (Pointer) iter.next();
        if (ptr.getValue() != null) {
            JXPathContext itemCtx = ctx.getRelativeContext(ptr);

            // Get the value as a string
            Object value = itemCtx.getValue(this.valuePath);

            // List may contain null value, and (per contract with convertors),
            // convertors are not invoked on nulls.
            if (value != null) {
                stringValue = this.datatype.convertToString(value, locale);
            }

            // Get the label (can be ommitted)
            itemCtx.setLenient(true);
            label = itemCtx.getValue(this.labelPath);
            if (label == null) {
                label = stringValue;
            }
        }

        // Output this item
        AttributesImpl itemAttrs = new AttributesImpl();
        itemAttrs.addCDATAAttribute("value", stringValue);
        contentHandler.startElement(Constants.WI_NS, ITEM_EL, Constants.WI_PREFIX_COLON + ITEM_EL, itemAttrs);
        if (label != null) {
            contentHandler.startElement(Constants.WI_NS, LABEL_EL, Constants.WI_PREFIX_COLON + LABEL_EL,
                    Constants.EMPTY_ATTRS);
            if (label instanceof XMLizable) {
                ((XMLizable) label).toSAX(contentHandler);
            } else {
                String stringLabel = label.toString();
                contentHandler.characters(stringLabel.toCharArray(), 0, stringLabel.length());
            }
            contentHandler.endElement(Constants.WI_NS, LABEL_EL, Constants.WI_PREFIX_COLON + LABEL_EL);
        }
        contentHandler.endElement(Constants.WI_NS, ITEM_EL, Constants.WI_PREFIX_COLON + ITEM_EL);
    }

    // End the selection-list
    contentHandler.endElement(Constants.WI_NS, SELECTION_LIST_EL,
            Constants.WI_PREFIX_COLON + SELECTION_LIST_EL);
}

From source file:org.chiba.xml.xforms.action.SetValueAction.java

/**
 * Performs the <code>setvalue</code> action.
 *
 * @return <code>true</code> if setvalue executed successfully, otherwise
 * <code>false</code>.//from w w w .  j  a v  a 2s.c o m
 * @throws XFormsException if an error occurred during <code>setvalue</code>
 * processing.
 */
public boolean perform() throws XFormsException {
    // get location path and instance id
    String locationPath = getLocationPath();
    String instanceId = getInstanceId(locationPath);

    // get instance
    Instance instance = getModel().getInstance(instanceId);

    if (instance.existsNode(locationPath)) {
        if (this.valueAttribute != null) {
            // evaluate value expression
            JXPathContext context = instance.getInstanceContext();
            Pointer instancePointer = context.getPointer(locationPath);
            JXPathContext valueContext = context.getRelativeContext(instancePointer);
            valueContext.setFunctions(context.getFunctions());
            Object value = valueContext.getValue(this.valueAttribute);
            String newValue = value != null ? value.toString() : "null";

            if (getLogger().isDebugEnabled()) {
                getLogger().debug(this + " perform: setting evaluated value '" + newValue + "'");
            }

            // set node value
            instance.setNodeValue(locationPath, newValue);
        } else {
            if (getLogger().isDebugEnabled()) {
                getLogger().debug(this + " perform: setting literal value '" + this.nodeValue + "'");
            }

            // set node value
            instance.setNodeValue(locationPath, this.nodeValue);
        }

        // update behaviour
        setDeferredRecalculate(this.model.getId(), true);
        setDeferredRevalidate(this.model.getId(), true);
        setDeferredRefresh(this.model.getId(), true);

        // indicate success
        return true;
    }
    // todo: error handling ?
    getLogger().warn(this + " perform: nodeset " + getLocationPath() + " does not exist");

    // indicate failure
    return false;
}

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  w w w. j  a  va 2 s .c  om*/
 * 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());
        }
    }
}