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

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

Introduction

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

Prototype

public abstract Iterator iterate(String xpath);

Source Link

Document

Traverses the xpath and returns an Iterator of all results found for the path.

Usage

From source file:org.dcm4chee.xds2.persistence.RegistryObject.java

/**
 * Indexed properties that are used in queries. 
 * Do not use the setter - the update is fully seamless - when object is merged/persisted - indexes are re/-created and updated if needed  
 * @return//from  w w  w . java 2  s .co m
 */
@OneToMany(mappedBy = "subject", cascade = CascadeType.ALL, orphanRemoval = true)
@Access(AccessType.PROPERTY)
@SuppressWarnings("unchecked")
public Set<RegistryObjectIndex> getIndexedValues() {
    log.debug("getIndexedValues called for object with id {}", getId());

    // TODO: OPTIMIZATION - if marshalling is fast - can check whether the object has already changed first

    // if fullObject was not initialized - nothing has changed and we could just return old value 
    // (except if reindexing is forced)
    if (fullObject == null && !FORCE_REINDEX)
        return currIndexedValues;

    if (getIndexes() == null)
        return currIndexedValues;

    // validate/update searchIndex table
    // iterate over all enabled indexes
    Set<RegistryObjectIndex> newIndexValues = new HashSet<RegistryObjectIndex>();
    for (XDSSearchIndexKey key : getIndexes()) {
        // run xpath expr on fullobject
        JXPathContext context = JXPathContext.newContext(getFullObject());
        Iterator<String> valueIterator = (Iterator<String>) context.iterate(INDEX_XPATHS.get(key));

        // add to newIndexValues
        while (valueIterator.hasNext()) {
            RegistryObjectIndex ind = new RegistryObjectIndex();
            ind.setSubject(this);
            ind.setKey(key);
            ind.setValue((String) valueIterator.next());
            newIndexValues.add(ind);
        }
    }

    // Retain what we have there already, and add new ones.
    // Note thats retain makes use of a custom equals for RegistryObjectIndex that does not consider the pk.
    currIndexedValues.retainAll(newIndexValues);
    currIndexedValues.addAll(newIndexValues);

    return currIndexedValues;
}

From source file:org.firesoa.common.jxpath.JXPathTestCase.java

protected void assertXPathValueIterator(JXPathContext ctx, String xpath, Collection expected) {
    Collection actual;/*from w w w.  jav  a2s  .c  o  m*/
    if (expected instanceof List) {
        actual = new ArrayList();
    } else {
        actual = new HashSet();
    }
    Iterator it = ctx.iterate(xpath);
    while (it.hasNext()) {
        actual.add(it.next());
    }
    assertEquals("Evaluating value iterator <" + xpath + ">", expected, actual);
}

From source file:org.geotools.xml.impl.jxpath.JXPathStreamingParserHandler.java

protected boolean stream(ElementHandler handler) {
    //create an xpath context from the root element
    // TODO: cache the context, should work just the same
    //        JXPathIntrospector.registerDynamicClass(ElementHandlerImpl.class,
    //            ElementHandlerPropertyHandler.class);
    JXPathIntrospector.registerDynamicClass(NodeImpl.class, NodePropertyHandler.class);

    //        ElementHandler rootHandler = 
    //           ((DocumentHandler) handlers.firstElement()).getDocumentElementHandler();
    Node root = ((DocumentHandler) handlers.firstElement()).getParseNode();
    JXPathContext jxpContext = JXPathContextFactory.newInstance().newContext(null, root);

    jxpContext.setLenient(true);//from  www .ja  v a2 s. com

    Iterator itr = jxpContext.iterate(xpath);

    for (; itr.hasNext();) {
        Object obj = itr.next();

        if (handler.getParseNode().equals(obj)) {
            return true;
        }
    }

    return false;
}

From source file:org.kuali.ole.docstore.discovery.solr.work.license.onixpl.WorkLicenseOnixplDocBuilder.java

public SolrInputDocument buildSolrInputDocument(ONIXPublicationsLicenseMessage license,
        AdditionalAttributes addAtrbts, String content) {
    SolrInputDocument solrDoc = new SolrInputDocument();
    solrDoc.addField(DOC_TYPE, DocType.LICENSE.getDescription());
    solrDoc.addField(DOC_FORMAT, DocFormat.ONIXPL.getCode());
    solrDoc.setField(DOC_CATEGORY, DocCategory.WORK.getCode());
    JXPathContext message = JXPathContext.newContext(license);
    for (Field field : onixPlMetaData.getFields()) {
        String xp = field.get("xpath");
        if (xp != null && xp.trim().length() != 0) {
            boolean hasValues = false;
            if (!xp.startsWith("/request/requestDocuments/ingestDocument/additionalAttributes/")) {
                Iterator values = message.iterate(xp);
                while (values.hasNext()) {
                    hasValues = true;// ww w. j a v  a 2 s  .c o  m
                    Object value = values.next();
                    solrDoc.addField(field.getName(), value);
                }
            } else if (addAtrbts != null) {
                solrDoc.addField(field.getName(),
                        addAtrbts.getAttribute(xp.substring(xp.lastIndexOf('/') + 1)));
                hasValues = true;
            }
            if (!hasValues)
                solrDoc.addField(field.getName(), null);
        }
    }
    if (content != null)
        allText.append(xmlUtility.getAllContentText(content));
    if (addAtrbts != null)
        allText.append(getAllTextForAdditionalAttributes(addAtrbts));
    solrDoc.addField(ALL_TEXT, allText.toString());
    return solrDoc;
}

From source file:org.kuali.ole.docstore.engine.service.index.solr.LicenseOnixplIndexer.java

protected void buildSolrInputDocument(Object object, List<SolrInputDocument> solrInputDocuments) {
    License license = (License) object;//from   w  ww . j a va2 s.co  m
    LicenseOnixplRecordConverter licenseOnixplRecordConverter = new LicenseOnixplRecordConverter();

    String content = license.getContent();
    ONIXPublicationsLicenseMessage onixPublicationsLicenseMessage = licenseOnixplRecordConverter
            .unmarshal(content);

    SolrInputDocument solrDoc = new SolrInputDocument();
    solrDoc.addField(DOC_TYPE, DocType.LICENSE.getDescription());
    solrDoc.addField(DOC_FORMAT, DocFormat.ONIXPL.getCode());
    solrDoc.setField(DOC_CATEGORY, DocCategory.WORK.getCode());
    JXPathContext message = JXPathContext.newContext(onixPublicationsLicenseMessage);
    for (Field field : onixPlMetaData.getFields()) {
        String xp = field.get("xpath");
        if (xp != null && xp.trim().length() != 0) {
            Iterator values = message.iterate(xp);
            while (values.hasNext()) {
                Object value = values.next();
                solrDoc.addField(field.getName(), value);
            }
        }
    }
    //TODO:set additional attributes

    if (content != null) {
        allText.append(xmlUtility.getAllContentText(content));
    }
    solrDoc.addField(ALL_TEXT, allText.toString());
    solrDoc.addField("dateEntered", new Date());
    solrDoc.addField("createdBy", license.getCreatedBy());
    solrDoc.setField("id", license.getId());
    solrDoc.setField("uniqueId", license.getId());
    solrDoc.setField("LocalId_search", DocumentLocalId.getDocumentId(license.getId()));
    solrDoc.setField("LocalId_display", DocumentLocalId.getDocumentIdDisplay(license.getId()));

    solrInputDocuments.add(solrDoc);

}

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

/**
 * Select objects with xpath./*from w  ww  . j av a 2 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;
    }
}

From source file:org.prevayler.demos.jxpath.Main.java

/**
 * Lists an object graph using an XPath expression.
 * /*from   w w w  .j  ava  2s. c o m*/
 * @param prevayler PrevalentSystem to query
 * @param xpathExp XPath expression to use
 */
private static void list(Prevayler prevayler, String xpathExp) {
    System.out.println("Executing XPath expression...");

    ProjectManagementSystem pms = (ProjectManagementSystem) prevayler.prevalentSystem();
    JXPathContext context = JXPathContext.newContext(pms);
    Iterator i = context.iterate(xpathExp);

    while (i.hasNext()) {

        Object obj = (Object) i.next();
        System.out.println(obj.toString());
    }
}

From source file:org.sweble.wikitext.example.XPath.java

static String query(EngProcessedPage cp, String query) {
    Iterator<?> results = null;
    try {/* ww w  .  j a va2 s.co m*/
        JXPathContext context = JXPathContext.newContext(cp.getPage());

        results = context.iterate(query);
    } catch (Throwable t) {
        System.err.println("An error occurred when executing XPath query.");
        t.printStackTrace();
    }

    if (results != null) {
        if (!results.hasNext()) {
            System.err.println("XPath result empty!");
        } else {
            List<Object> r = new ArrayList<Object>();
            while (results.hasNext())
                r.add(results.next());

            System.err.println("Found " + r.size() + " matching nodes.");

            StringBuilder b = new StringBuilder();

            int i = 1;
            for (Object o : r) {
                WtNode n = (WtNode) o;
                b.append('(');
                b.append(query);
                b.append(")[");
                b.append(i);
                b.append("]:\n\"\"\"");
                b.append(WtRtDataPrinter.print(n));
                b.append("\"\"\"\n\n");
                ++i;
            }

            return b.toString();
        }
    }

    return "";
}

From source file:org.sweble.wikitext.parser.XPathTest.java

private void doQuery(JXPathContext context, StringBuilder b, final String query) {
    b.append(StringUtils.strrep('-', 80));
    b.append("\n  ");
    b.append(query);//  ww  w.j  a  v a 2s . co m
    b.append('\n');
    b.append(StringUtils.strrep('-', 80));
    b.append('\n');

    int j = 1;
    for (Iterator<?> i = context.iterate(query); i.hasNext();) {
        if (j > 1) {
            b.append(StringUtils.strrep('-', 80));
            b.append('\n');
        }
        b.append(WtAstPrinter.print((WtNode) i.next()));
        b.append('\n');
        ++j;
    }

    b.append(StringUtils.strrep('=', 80));
    b.append('\n');
}

From source file:org.toobsframework.pres.util.ParameterUtil.java

public static void mapParameters(IRequest request, String callingContext, Parameter[] paramMap, Map inParams,
        Map outParams, String scopeId, List<IDataProviderObject> objects) throws ParameterException {
    if (paramMap != null) {
        JXPathContext context = JXPathContext.newContext(inParams);
        for (int j = 0; j < paramMap.length; j++) {
            Parameter thisParam = paramMap[j];
            Object value = null;// w w w. j a  va 2  s .  co m
            String thisPath = null;
            String thisName = null;
            try {
                if (thisParam.getScope() != null && !thisParam.getScope().equalsIgnoreCase("all")
                        && !thisParam.getScope().equalsIgnoreCase(scopeId)) {
                    continue;
                }
                if (!thisParam.getOverwriteExisting() && inParams.get(thisParam.getName()) != null) {
                    continue;
                }
                thisName = resolveParam(request, thisParam.getName(), inParams)[0];
                thisPath = resolveParam(request, thisParam.getPath(), inParams)[0];
                boolean condition = true;
                if (thisParam.getCondition() != null) {
                    Object condObj = context.getValue(thisParam.getCondition());
                    if (log.isDebugEnabled()) {
                        log.debug("Condition Object: " + condObj);
                    }
                    if (condObj != null && condObj instanceof Boolean) {
                        condition = (Boolean) condObj;
                    }
                }
                if (condition) {
                    if (thisParam.getIsStatic()) {
                        value = thisPath;
                    } else if (thisParam.getIsObject()) {
                        if ((objects == null)
                                || (objects != null && thisParam.getObjectIndex() >= objects.size())) {
                            continue;
                        }
                        JXPathContext objContext = JXPathContext
                                .newContext(objects.get(thisParam.getObjectIndex()));
                        if (thisParam.getIsList()) {
                            Iterator iter = objContext.iterate(thisPath);
                            value = new ArrayList();
                            while (iter.hasNext()) {
                                ((ArrayList) value).add(iter.next());
                            }
                            if (((ArrayList) value).size() == 0 && thisParam.getDefault() != null) {
                                ((ArrayList) value).add(thisParam.getDefault());
                            }
                        } else {
                            value = objContext.getValue(thisPath);
                        }
                    } else if (thisParam.getIsList()) {
                        Object newList = inParams.get(thisName);
                        if (newList == null)
                            newList = outParams.get(thisName);
                        if (newList != null && !(newList instanceof ArrayList)) {
                            newList = new ArrayList();
                            ((ArrayList) newList).add(value);
                        }
                        if (newList == null)
                            newList = new ArrayList();

                        value = context.getValue(thisPath);
                        if (value != null && value.getClass().isArray()) {
                            Object[] valueArray = (Object[]) value;
                            if (valueArray.length > 1) {
                                for (int i = 0; i < valueArray.length; i++) {
                                    if (valueArray[i] != null && ((String) valueArray[i]).length() > 0)
                                        ((ArrayList) newList).add(valueArray[i]);
                                }
                                value = null;
                            } else {
                                value = valueArray[0];
                            }
                        }
                        if (value != null && !"".equals(value))
                            ((ArrayList) newList).add(value);

                        value = newList;
                    } else {
                        value = context.getValue(thisPath);
                        if (value != null && value.getClass().isArray()) {
                            Object[] valueArray = (Object[]) value;
                            if (valueArray.length > 1) {
                                value = valueArray;
                            } else {
                                value = valueArray[0];
                            }
                        } else if (value == null && thisParam.getSessionPath() != null) {
                            value = context.getValue(thisParam.getSessionPath());
                        }
                    }
                    if (value != null && value.getClass().isArray() && thisParam.getIsList()) {
                        outParams.put(thisName, value);
                    } else if (value != null && value.getClass().isArray()) {
                        outParams.put(thisName, ((String[]) value)[0]);
                    } else if (value != null && value instanceof ArrayList && ((ArrayList) value).size() > 0) {
                        outParams.put(thisName, value);
                    } else if (value != null && value instanceof String) {
                        outParams.put(thisName, (String) value);
                    } else if (value != null && !(value instanceof ArrayList)
                            && String.valueOf(value).length() > 0) {
                        outParams.put(thisName, String.valueOf(value));
                    } else if (thisParam.getDefault() != null) {
                        String[] defVal = resolveParam(request, thisParam.getDefault(), inParams);
                        if (defVal != null) {
                            outParams.put(thisName, defVal[0]);
                        }
                    } else if (!thisParam.getIgnoreNull()) {
                        throw new ParameterException(callingContext, thisName, thisPath);
                    } else if (log.isDebugEnabled()) {
                        log.debug("Param " + thisName + " evaluated to null");
                    }
                }
            } catch (Exception e) {
                log.error("mapParameters - exception [name:" + thisName + " path:" + thisPath + " value:"
                        + value + "]");
                throw new ParameterException(callingContext, thisName, thisPath);
            }
        }
    }
}