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

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

Introduction

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

Prototype

public abstract Object getValue(String xpath);

Source Link

Document

Evaluates the xpath and returns the resulting object.

Usage

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//  w w 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;/*from w  w w.j ava 2 s  .  com*/
    Iterator iter = null;
    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.test.conformance.chapter3.Chapter3Test.java

/**
 * __UNDOCUMENTED__/*  ww w. j a  v a 2s  . c  om*/
 *
 * @throws Exception __UNDOCUMENTED__
 */
public void test010c() throws Exception {
    URI uri = new URI(getClass().getResource("c3-010c.xml").toString());
    File file = new File(uri);
    String baseUri = file.getParentFile().toURI().toString();

    processor.setBaseURI(baseUri);
    processor.setXMLContainer(file.getAbsolutePath());
    processor.init();

    //        DOMUtil.prettyPrintDOM(processor.getXMLContainer());
    JXPathContext context = processor.getContainer().getRootContext();
    assertTrue(context.getValue("//chiba:data[1]").equals("external"));
}

From source file:org.chiba.test.conformance.chapter3.Chapter3Test.java

/**
 * test usage of default namespace./*from  w ww  .j a va  2s  . c  om*/
 * test, if control contains the value that is referenced via bind.
 *
 * @throws java.lang.Exception
 */
public void testNamespace1() throws Exception {
    System.out.println("Chapter 3: Testing use of Namespaces including Default Namespace");
    processor.setXMLContainer(getClass().getResourceAsStream("c3-001.xml"));
    processor.init();

    //       Document doc = processor.getContainer().getDOM();
    //        DOMUtil.prettyPrintDOM(processor.getXMLContainer());
    JXPathContext context = processor.getContainer().getRootContext();

    //check the controls value
    String result = (String) context.getValue("//xf:input/chiba:data/text()");
    assertNotNull(result);
    assertTrue(result.equals("42"));
}

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

protected boolean evalIfCondition(Element action, String ifCondition) {
    //get the global XPath context
    JXPathContext context = this.model.getDefaultInstance().getInstanceContext();
    String currentPath = getLocationPath();

    //make the ifCondition a Predicate of the currentPath
    String expr = XPathUtil.joinStep(new String[] { currentPath, ifCondition });
    Boolean b = (Boolean) context.getValue("boolean(" + expr + ")");

    return b.booleanValue();
}

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>./*  www. ja  v  a 2 s  .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.BindingTest.java

public void testNestedContext() throws Exception {
    JXPathContext context = this.chibaBean.getContainer().getRootContext();
    assertEquals("1", context.getValue("//*[@id='repeat-1']/xf:group[1]//xf:output/chiba:data/text()"));
    assertEquals("2", context.getValue("//*[@id='repeat-1']/xf:group[2]//xf:output/chiba:data/text()"));
    assertEquals("3", context.getValue("//*[@id='repeat-1']/xf:group[3]//xf:output/chiba:data/text()"));
    assertEquals("1", context.getValue("//*[@id='repeat-2']/xf:group[1]//xf:output/chiba:data/text()"));
    assertEquals("2", context.getValue("//*[@id='repeat-2']/xf:group[2]//xf:output/chiba:data/text()"));
    assertEquals("3", context.getValue("//*[@id='repeat-2']/xf:group[3]//xf:output/chiba:data/text()"));
}

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

private void assertValues(String input, String label, int number) throws XFormsException {
    JXPathContext context = this.chibaBean.getContainer().getRootContext();
    assertEquals(input, context.getValue("//*[@id='input-" + number + "']/chiba:data/text()"));
    assertEquals(label, context.getValue("//*[@id='input-" + number + "']/xf:label/text()"));
}

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

/**
 * tests the dispatching of an event to an element.
 *
 * @throws Exception __UNDOCUMENTED__// w w w .ja  va 2s.co m
 */
public void testDispatchEvent() throws Exception {
    processor.setXMLContainer(getClass().getResourceAsStream("actions.xhtml"));
    processor.init();
    assertTrue(!processor.dispatch("setvalue-trigger", DOMEventNames.ACTIVATE));

    //test the side effect of dispatching the DOMActivate to a setvalue trigger -> the instance has a new value
    Document instance = processor.getContainer().getDefaultModel().getDefaultInstance().getInstanceDocument();
    JXPathContext context = JXPathContext.newContext(instance);
    assertTrue(context.getValue("//helloworld").equals("Hello World"));
}

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

/**
 * test, if updateControlValue correctly changes the value and a value-changed event occurs on the relevant
 * control.//w  w  w  .  jav a2 s . com
 *
 * @throws Exception
 */
public void testUpdateControlValue1() throws Exception {
    processor.setXMLContainer(getClass().getResourceAsStream("actions.xhtml"));
    processor.init();

    TestEventListener listener = new TestEventListener();
    JXPathContext context = JXPathContext.newContext(this.processor.getXMLContainer());
    Node node = (Node) context.getPointer("//*[@id='hello-input']").getNode();
    EventTarget eventTarget = (EventTarget) node;
    eventTarget.addEventListener(XFormsEventNames.VALUE_CHANGED, listener, false);

    processor.updateControlValue("hello-input", "Hello new World");
    assertTrue(listener.getType().equals(XFormsEventNames.VALUE_CHANGED));
    assertTrue(listener.getId().equals("hello-input"));

    //test the side effect of dispatching the DOMActivate to a setvalue trigger -> the instance has a new value
    Document instance = processor.getContainer().getDefaultModel().getDefaultInstance().getInstanceDocument();
    JXPathContext context1 = JXPathContext.newContext(instance);
    assertTrue(context1.getValue("//helloworld").equals("Hello new World"));
}