Example usage for org.dom4j Node matches

List of usage examples for org.dom4j Node matches

Introduction

In this page you can find the example usage for org.dom4j Node matches.

Prototype

boolean matches(String xpathExpression);

Source Link

Document

matches returns true if evaluating the given XPath expression on this node returns a non-empty node set containing this node.

Usage

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

/**
 * return list view of items including hard deleted
 * @param root//from   w w  w.  jav a 2s . com
 * @param creds
 * @param cache
 * @param path
 * @param nodeName
 * @param matchlistitem
 * @param csidfield
 * @param fullcsid
 * @param view_map
 * @return
 * @throws ConnectionException
 * @throws JSONException
 */
// CSPACE-5988: Allow view_map to be passed as a parameter, instead of using the instance variable.
protected JSONObject getRepeatableHardListView(ContextualisedStorage root, CSPRequestCredentials creds,
        CSPRequestCache cache, String path, String nodeName, String matchlistitem, String csidfield,
        Boolean fullcsid, Map<String, String> view_map) throws ConnectionException, JSONException {
    JSONObject out = new JSONObject();
    JSONObject pagination = new JSONObject();
    Document list = null;
    List<JSONObject> listitems = new ArrayList<JSONObject>();
    ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
    if (all.getStatus() != 200) {
        //throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
        throw new ConnectionException("Bad request during identifier cache map update: status not 200 is "
                + Integer.toString(all.getStatus()), all.getStatus(), path);
    }
    list = all.getDocument();

    List<Node> nodes = list.selectNodes(nodeName);
    if (matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")) {
        //XXX hack to deal with roles being inconsistent
        //XXX CSPACE-1887 workaround
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                String csid = node.valueOf("@csid");
                JSONObject test = new JSONObject();
                test.put("csid", csid);
                listitems.add(test);
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    } else {
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                List<Node> fields = node.selectNodes("*");
                String csid = "";
                String urlPlusCSID = null;
                if (node.selectSingleNode(csidfield) != null) {
                    csid = node.selectSingleNode(csidfield).getText();
                    urlPlusCSID = r.getServicesURL() + "/" + csid;
                }
                JSONObject test = new JSONObject();
                for (Node field : fields) {
                    if (csidfield.equals(field.getName())) {
                        if (!fullcsid) {
                            int idx = csid.lastIndexOf("/");
                            if (idx != -1) {
                                csid = csid.substring(idx + 1);
                                urlPlusCSID = r.getServicesURL() + "/" + csid;
                            }
                        }
                        test.put("csid", csid);
                    } else {
                        String json_name = view_map.get(field.getName());
                        if (json_name != null) {
                            String value = field.getText();
                            // XXX hack to cope with multi values      
                            if (value == null || "".equals(value)) {
                                List<Node> inners = field.selectNodes("*");
                                for (Node n : inners) {
                                    value += n.getText();
                                }
                            }
                            String gleanname = urlPlusCSID;
                            if (csidfield.equals("uri")) {
                                gleanname = csid;
                            }
                            setGleanedValue(cache, gleanname, json_name, value);
                            test.put(json_name, value);
                        }
                    }
                }
                listitems.add(test);
                if (allfields == null || allfields.length == 0) {
                    if (log.isWarnEnabled()) {
                        log.warn(
                                "getRepeatableHardListView(): Missing fieldsReturned value - may cause fan-out!\nRecord:"
                                        + r.getID() + " request to: " + path);
                    }
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    String gleanname = urlPlusCSID;
                    if (csidfield.equals("uri")) {
                        gleanname = csid;
                    }
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, gleanname, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, gleanname, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    }
    out.put("pagination", pagination);
    out.put("listItems", listitems);
    return out;
}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

/**
 * return list view of items//w ww .  ja  v  a2  s.  c  o  m
 * TODO make getHardListView and getRepeatableHardListView to share more code as they aren't different enough to warrant the level of code repeat
 * @param creds
 * @param cache
 * @param path
 * @param nodeName
 * @param matchlistitem
 * @param csidfield
 * @param fullcsid
 * @return
 * @throws ConnectionException
 * @throws JSONException
 */
protected JSONObject getHardListView(CSPRequestCredentials creds, CSPRequestCache cache, String path,
        String nodeName, String matchlistitem, String csidfield, Boolean fullcsid)
        throws ConnectionException, JSONException {
    JSONObject out = new JSONObject();
    JSONObject pagination = new JSONObject();
    Document list = null;
    List<String> listitems = new ArrayList<String>();
    ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
    if (all.getStatus() != 200) {
        //throw new StatusException(all.getStatus(),path,"Bad request during identifier cache map update: status not 200");
        throw new ConnectionException("Bad request during identifier cache map update: status not 200 is "
                + Integer.toString(all.getStatus()), all.getStatus(), path);
    }
    list = all.getDocument();

    List<Node> nodes = list.selectNodes(nodeName);
    if (matchlistitem.equals("roles_list/*") || matchlistitem.equals("permissions_list/*")) {
        //XXX hack to deal with roles being inconsistent
        //XXX CSPACE-1887 workaround
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                String csid = node.valueOf("@csid");
                listitems.add(csid);
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    } else {
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        for (Node node : nodes) {
            if (node.matches(matchlistitem)) {
                List<Node> fields = node.selectNodes("*");
                String csid = "";
                String urlPlusCSID = null;
                if (node.selectSingleNode(csidfield) != null) {
                    csid = node.selectSingleNode(csidfield).getText();
                    urlPlusCSID = r.getServicesURL() + "/" + csid;
                    setGleanedValue(cache, urlPlusCSID, "csid", csid);
                }
                for (Node field : fields) {
                    if (csidfield.equals(field.getName())) {
                        if (!fullcsid) {
                            int idx = csid.lastIndexOf("/");
                            if (idx != -1) {
                                csid = csid.substring(idx + 1);
                                urlPlusCSID = r.getServicesURL() + "/" + csid;
                            }
                        }
                        listitems.add(csid);
                    } else {
                        String json_name = view_map.get(field.getName());
                        if (json_name != null) {
                            String value = field.getText();
                            // XXX hack to cope with multi values      
                            if (value == null || "".equals(value)) {
                                List<Node> inners = field.selectNodes("*");
                                for (Node n : inners) {
                                    value += n.getText();
                                }
                            }
                            setGleanedValue(cache, urlPlusCSID, json_name, value);
                        }
                    }
                }
                if (allfields == null || allfields.length == 0) {
                    if (log.isWarnEnabled()) {
                        log.warn("getHardListView(): Missing fieldsReturned value - may cause fan-out!\nRecord:"
                                + r.getID() + " request to: " + path);
                    }
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, urlPlusCSID, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, urlPlusCSID, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }
    }
    out.put("pagination", pagination);
    out.put("listItems", listitems.toArray(new String[0]));
    return out;

}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

public void handleHierarchyPayloadRetrieve(Record r, ReturnedMultipartDocument doc, JSONObject out,
        String thiscsid) throws JSONException {
    if (r.hasHierarchyUsed("screen")) {
        //lets do relationship stuff...
        Document list = doc.getDocument("relations-common-list");
        if (list == null)
            return;
        List<Node> nodes = list.selectNodes("/relations-common-list/*");

        for (Node node : nodes) {
            if (node.matches("/relations-common-list/relation-list-item")) {
                //String test = node.asXML();
                String relationshipType = node.selectSingleNode("relationshipType").getText();
                // Be forgiving while waiting for services to complete code.
                Node relationshipMetaTypeNode = node.selectSingleNode("relationshipMetaType");
                String relationshipMetaType = (relationshipMetaTypeNode != null)
                        ? relationshipMetaTypeNode.getText()
                        : "";
                //String subjCSID = node.selectSingleNode("subjectCsid").getText();
                //String objCSID = node.selectSingleNode("objectCsid").getText();
                String subjURI = "";
                String subjCSID = "";
                String subjDocType = "";
                if (node.selectSingleNode("subject/uri") != null) {
                    subjCSID = node.selectSingleNode("subject/csid").getText();
                    subjDocType = node.selectSingleNode("subject/documentType").getText();
                    subjURI = node.selectSingleNode("subject/refName").getText();
                }//w  w w.j a  v  a  2  s.c  o m
                String objRefName = "";
                String objDocType = "";
                String objCSID = "";
                if (node.selectSingleNode("object/uri") != null) {
                    objCSID = node.selectSingleNode("object/csid").getText();
                    objDocType = node.selectSingleNode("object/documentType").getText();
                    objRefName = node.selectSingleNode("object/refName").getText();
                }

                String relateduri = objRefName;
                String relatedcsid = objCSID;
                String relatedser = objDocType;

                if (r.getSpec().hasRelationshipByPredicate(relationshipType)) {
                    Relationship rel = r.getSpec().getRelationshipByPredicate(relationshipType);
                    Relationship newrel = rel;
                    //is this subject or object
                    if (thiscsid.equals(objCSID)) {
                        //should we invert
                        if (r.getSpec().hasRelationshipInverse(rel.getID())) {
                            newrel = r.getSpec().getInverseRelationship(rel.getID());
                            relateduri = subjURI;
                            relatedcsid = subjCSID;
                            relatedser = subjDocType;
                        }
                    }

                    String metaTypeField = newrel.getMetaTypeField();

                    if (newrel.getObject().equals("n")) { //array
                        JSONObject subdata = new JSONObject();
                        subdata.put(newrel.getChildName(), relateduri);
                        if (!StringUtils.isEmpty(metaTypeField)) {
                            subdata.put(metaTypeField, relationshipMetaType);
                        }
                        if (out.has(newrel.getID())) {
                            out.getJSONArray(newrel.getID()).put(subdata);
                        } else {
                            JSONArray relList = new JSONArray();
                            relList.put(subdata);
                            out.put(newrel.getID(), relList);
                        }
                    } else {//string
                        out.put(newrel.getID(), relateduri);
                        if (!StringUtils.isEmpty(metaTypeField)) {
                            out.put(metaTypeField, relationshipMetaType);
                        }
                        if (newrel.showSiblings()) {
                            out.put(newrel.getSiblingChild(), relatedser + "/" + relatedcsid);
                            //out.put(newrel.getSiblingChild(), relateduri);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.relation.ServicesRelationStorage.java

License:Educational Community License

@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    JSONObject out = new JSONObject();
    Boolean isHierarchical = false;
    if (isPathType(rootPath, new String[] { "main" }, 0)) {
        extractPaths(rootPath, new String[] { "main" }, 0);
    } else if (isPathType(rootPath, new String[] { "hierarchical" }, 0)) {
        extractPaths(rootPath, new String[] { "hierarchical" }, 0);
        isHierarchical = true;//from  ww w .  j av  a  2 s  .  c o m
    }

    try {
        JSONObject moredata = new JSONObject();
        List<String> list = new ArrayList<String>();
        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, "/relations?" + searchPath(restrictions),
                null, creds, cache);
        Document doc = data.getDocument();
        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
        JSONObject pagination = new JSONObject();
        String xmlroot = "relations-common-list";
        List<Node> nodes = doc.getDocument().selectNodes("/" + xmlroot + "/*");
        for (Node node : nodes) {
            if (node.matches("/" + xmlroot + "/relation-list-item")) {
                //if(post_filter(creds,cache,restrictions,node))
                list.add(node.selectSingleNode("csid").getText());
                if (isHierarchical) {
                    JSONObject hdata = new JSONObject();
                    Node subjectNode = node.selectSingleNode("subject");
                    Node objectNode = node.selectSingleNode("object");
                    hdata.put("subjecturi", subjectNode.selectSingleNode("uri").getText());
                    hdata.put("objecturi", objectNode.selectSingleNode("uri").getText());
                    hdata.put("subjectcsid", subjectNode.selectSingleNode("csid").getText());
                    hdata.put("objectcsid", objectNode.selectSingleNode("csid").getText());

                    findNameUnderNode(hdata, "subjectname", "subjectrefname", subjectNode);
                    findNameUnderNode(hdata, "objectname", "objectrefname", objectNode);

                    hdata.put("type", node.selectSingleNode("predicate").getText());
                    hdata.put("csid", node.selectSingleNode("csid").getText());
                    moredata.put(node.selectSingleNode("csid").getText(), hdata);
                }
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }

        out.put("pagination", pagination);
        out.put("listItems", list.toArray(new String[0]));
        out.put("moredata", moredata);
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Could not retrieve relation" + e.getLocalizedMessage(),
                e.getStatus(), e.getUrl());
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Could not retrieve relation", e);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.vocab.ConfiguredVocabStorage.java

License:Educational Community License

/**
 * Returns JSON containing pagenumber, pagesize, itemsinpage, totalitems and the list of items itself 
 *//*from  www  . ja v a2s  . c  om*/
@SuppressWarnings("unchecked")
public JSONObject getPathsJSON(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        JSONObject out = new JSONObject();
        List<String> list = new ArrayList<String>();
        String url;
        if (rootPath.isEmpty()) {
            url = "/" + r.getServicesURL() + ALL_VOCAB_ITEMS;
        } else {
            String vocab = RefName.shortIdToPath(rootPath);
            url = "/" + r.getServicesURL() + "/" + vocab + ITEMS_SUFFIX;
        }

        String path = getRestrictedPath(url, restrictions, r.getServicesSearchKeyword(), "", true,
                getDisplayNameKey());

        boolean excludeSoftDeleted = true;

        if (restrictions.has("deleted")) {
            excludeSoftDeleted = !restrictions.getBoolean("deleted");
        }

        if (excludeSoftDeleted && r.hasSoftDeleteMethod()) {
            path = softpath(path);
        }

        ReturnedDocument data = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        Document doc = data.getDocument();

        if (doc == null)
            throw new UnderlyingStorageException("Could not retrieve vocabulary items", data.getStatus(), path);
        String[] tag_parts = r.getServicesListPath().split(",", 2);

        JSONObject pagination = new JSONObject();
        String[] allfields = null;
        String fieldsReturnedName = r.getServicesFieldsPath();
        List<Node> nodes = doc.selectNodes("/" + tag_parts[1].split("/")[0] + "/*");
        for (Node node : nodes) {
            if (node.matches("/" + tag_parts[1])) {
                // Risky hack - assumes displayName must be at root. Really should
                // understand that the list results are a different schema from record GET.
                String dnName = getDisplayNameKey();
                String csid = node.selectSingleNode("csid").getText();
                list.add(csid);
                String urlPlusCSID = url + "/" + csid;

                List<Node> nameNodes = node.selectNodes(dnName);
                String nameListValue = null;
                for (Node nameNode : nameNodes) {
                    String name = nameNode.getText();
                    if (nameListValue == null) {
                        nameListValue = name;
                    } else {
                        nameListValue = JSONUtils.appendWithArraySeparator(nameListValue, name);
                    }
                }
                if (nameListValue == null) {
                    throw new JSONException("No displayNames found!");
                } else {
                    String json_name = view_map.get(dnName);
                    setGleanedValue(cache, urlPlusCSID, json_name, nameListValue);
                }

                List<Node> fields = node.selectNodes("*[(name()!='" + dnName + "')]");
                for (Node field : fields) {
                    String json_name = view_map.get(field.getName());
                    if (json_name != null) {
                        String value = field.getText();
                        // XXX hack to cope with multi values      
                        if (value == null || "".equals(value)) {
                            List<Node> inners = field.selectNodes("*");
                            for (Node n : inners) {
                                value += n.getText();
                            }
                        }
                        setGleanedValue(cache, urlPlusCSID, json_name, value);
                    }
                }
                if (allfields == null || allfields.length == 0) {
                    log.warn("Missing fieldsReturned value - may cause fan-out!");
                } else {
                    // Mark all the fields not yet found as gleaned - 
                    for (String s : allfields) {
                        String gleaned = getGleanedValue(cache, urlPlusCSID, s);
                        if (gleaned == null) {
                            setGleanedValue(cache, urlPlusCSID, s, "");
                        }
                    }
                }
            } else if (fieldsReturnedName.equals(node.getName())) {
                String myfields = node.getText();
                allfields = myfields.split("\\|");
            } else {
                pagination.put(node.getName(), node.getText());
            }
        }

        out.put("pagination", pagination);
        out.put("listItems", list.toArray(new String[0]));
        return out;
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Connection exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("UTF-8 not supported!?" + e.getLocalizedMessage());
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Error parsing JSON" + e.getLocalizedMessage());
    }
}

From source file:ru.gelin.fictionbook.reader.models.FBSimpleStyler.java

License:Open Source License

/**
 *  Sets style for the Element. Uses XPath expressions ("pattern" style
 *  property) and XML Node corresponding to the Element.
 *///from ww  w.jav a2 s  .  co m
public void applyStyle(FBSimpleElement element) {
    Node node = element.getNode();
    for (String pattern : patternList) {
        if (node.matches(pattern)) {
            element.setAttributeSet(patternToStyle.get(pattern));
            if (log.isDebugEnabled()) {
                log.debug(node.getPath() + " <- " + patternToStyle.get(pattern).getName());
            }
            break;
        }
    }
}