Example usage for org.apache.commons.jxpath BasicVariables BasicVariables

List of usage examples for org.apache.commons.jxpath BasicVariables BasicVariables

Introduction

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

Prototype

BasicVariables

Source Link

Usage

From source file:org.paxml.core.Context.java

/**
 * Select objects with xpath./*from w  w w.j  a  va2  s  .  c o m*/
 * 
 * @param from
 *            the object to select properties from, null to select from
 *            entire context.
 * @param xpath
 *            the xpath
 * @param alwaysList
 *            true to return a list with one item inside if the xpath
 *            results in one object to be selected.
 * @return either a list of objects that satisfies the xpath, or the object
 *         itself if the xpath results in one object to be selected and the
 *         "alwaysList" parameter is false.
 */
public Object xpathSelect(Object from, String xpath, boolean alwaysList) {
    Variables vars = new BasicVariables();

    if (from == null) {
        ObjectTree nameGlobal = getRootContext().getNameMap(false, true);
        ObjectTree nameLocal = getNameMap(true, false);

        vars.declareVariable(XPATH_NAME_GLOBAL_VAR, nameGlobal);
        vars.declareVariable(XPATH_NAME_LOCAL_VAR, nameLocal);

        ObjectTree nameAuto = new ObjectTree(null, nameGlobal);
        nameAuto.addValues(nameLocal);

        from = nameAuto;
    }

    JXPathContext xpathContext = JXPathContext.newContext(from);
    xpathContext.setVariables(vars);
    xpathContext.setIdentityManager(this);

    setXpathFunctions(xpathContext);

    try {
        Object selected = xpathContext.iterate(xpath);

        List<Object> list = new ArrayList<Object>(1);
        if (selected instanceof Iterator) {
            final Iterator<?> it = (Iterator<?>) selected;
            while (it.hasNext()) {
                Object obj = it.next();
                list.add(getXpathResultObject(obj));
            }
            if (list.size() == 1) {
                selected = list.get(0);
            } else {
                selected = list;
            }
        } else {

            selected = getXpathResultObject(selected);

            if (selected != null && alwaysList) {
                list.add(selected);
            }
        }
        if (alwaysList) {
            return list;
        } else {
            if (selected instanceof List) {
                list = (List) selected;
                final int size = list.size();
                if (size == 0) {
                    return null;
                } else if (size == 1) {
                    return list.get(0);
                }
            }
            return selected;
        }
    } catch (NullPointerException e) {
        // when jxpath throws null pointer exception, it has problem
        // searching non-existing paths
        return null;
    }
}