Example usage for org.dom4j Node selectSingleNode

List of usage examples for org.dom4j Node selectSingleNode

Introduction

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

Prototype

Node selectSingleNode(String xpathExpression);

Source Link

Document

selectSingleNode evaluates an XPath expression and returns the result as a single Node instance.

Usage

From source file:org.aludratest.impl.log4testing.configuration.Log4TestingConfiguration.java

License:Apache License

public String replace(String output) {
    @SuppressWarnings("unchecked")
    List<Node> replaceNodes = xmlConfig.selectNodes(XPATH_REPLACE);
    String result = output;//from   w w  w  . j  a  va2s .c om
    for (Node replaceNode : replaceNodes) {
        String regex = replaceNode.selectSingleNode(XPATH_REPLACE_REGEX).getStringValue();
        String replacement = replaceNode.selectSingleNode(XPATH_REPLACE_REPLACEMENT).getStringValue();
        result = result.replaceAll(regex, replacement);
    }
    return result;
}

From source file:org.b5chat.crossfire.core.plugin.PluginCacheConfigurator.java

License:Open Source License

private void registerCache(String pluginName, Node configData) {
    String cacheName = configData.selectSingleNode("cache-name").getStringValue();
    String schemeName = configData.selectSingleNode("scheme-name").getStringValue();
    if (cacheName == null || schemeName == null) {
        throw new IllegalArgumentException(
                "Both cache-name and scheme-name elements are required. Found cache-name: " + cacheName
                        + " and scheme-name: " + schemeName);
    }//w w w  .j  a  v  a 2 s. c  o  m

    Map<String, String> initParams = readInitParams(configData);
    CacheInfo info = new CacheInfo(cacheName, CacheInfo.Type.valueof(schemeName), initParams);
    PluginCacheRegistry.getInstance().registerCache(pluginName, info);
}

From source file:org.b5chat.crossfire.core.plugin.PluginCacheConfigurator.java

License:Open Source License

private Map<String, String> readInitParams(Node configData) {
    Map<String, String> paramMap = new HashMap<String, String>();
    @SuppressWarnings("unchecked")
    List<Node> params = configData.selectNodes("init-params/init-param");
    for (Node param : params) {
        String paramName = param.selectSingleNode("param-name").getStringValue();
        String paramValue = param.selectSingleNode("param-value").getStringValue();
        paramMap.put(paramName, paramValue);
    }/*from w ww  . j a v  a 2s .  c om*/

    return paramMap;
}

From source file:org.ballproject.knime.base.config.DOMHelper.java

License:Open Source License

public static Node selectSingleNode(Node root, String query) throws Exception {
    Node result = root.selectSingleNode(query);
    if (result == null)
        throw new Exception("XPath query yielded null result");
    return result;
}

From source file:org.bigmouth.nvwa.utils.xml.Dom4jDecoder.java

License:Apache License

/**
 * <p>XML???</p>//from w  ww . j  av a2  s.  co m
 * ?
 * appId?
 * ?XMLappId?appid?APPID?app_id?APP_ID
 * @param <T>
 * @param xml
 * @param xpath
 * @param cls
 * @return
 */
public static <T> T decode(String xml, String xpath, Class<T> cls) throws Exception {
    if (StringUtils.isBlank(xml))
        return null;
    T t = cls.newInstance();
    Document doc = DocumentHelper.parseText(xml);
    Node itemNode = doc.selectSingleNode(xpath);

    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
        // if the field name is 'appId'
        String name = field.getName();
        String nodename = name;
        if (field.isAnnotationPresent(Argument.class)) {
            nodename = field.getAnnotation(Argument.class).name();
        }
        // select appId node
        Node current = itemNode.selectSingleNode(nodename);
        if (null == current) {
            // select appid node
            current = itemNode.selectSingleNode(nodename.toLowerCase());
        }
        if (null == current) {
            // select APPID node
            current = itemNode.selectSingleNode(nodename.toUpperCase());
        }
        if (null == current) {
            // select app_id node
            nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(nodename), "_").toLowerCase();
            current = itemNode.selectSingleNode(nodename);
        }
        if (null == current) {
            // select APP_ID node
            nodename = StringUtils.join(StringUtils.splitByCharacterTypeCamelCase(nodename), "_").toUpperCase();
            current = itemNode.selectSingleNode(nodename);
        }
        if (null != current) {
            String invokeName = StringUtils.join(new String[] { "set", StringUtils.capitalize(name) });
            try {
                MethodUtils.invokeMethod(t, invokeName, current.getText());
            } catch (NoSuchMethodException e) {
                LOGGER.warn("NoSuchMethod-" + invokeName);
            } catch (IllegalAccessException e) {
                LOGGER.warn("IllegalAccess-" + invokeName);
            } catch (InvocationTargetException e) {
                LOGGER.warn("InvocationTarget-" + invokeName);
            }
        }
    }
    return t;
}

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/* w w  w . ja va 2 s .c  o m*/
 * @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/*from   w  w  w. j a  va 2 s .  co 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();
                }/*from  ww  w.  jav  a 2  s .  com*/
                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.RecordStorage.java

License:Educational Community License

/**
 * Gets a list of csids of a certain type of record
 * /*from w  w  w  . j  ava2s. co m*/
 * XXX should not be used...
 */
@SuppressWarnings("unchecked")
public String[] getPaths(ContextualisedStorage root, CSPRequestCredentials creds, CSPRequestCache cache,
        String rootPath, JSONObject restrictions)
        throws ExistException, UnimplementedException, UnderlyingStorageException {
    try {
        Document list = null;
        List<String> out = new ArrayList<String>();

        String path = getRestrictedPath(r.getServicesURL(), restrictions, r.getServicesSearchKeyword(), "",
                false, "");

        ReturnedDocument all = conn.getXMLDocument(RequestMethod.GET, path, null, creds, cache);
        if (all.getStatus() != 200) {
            throw new ConnectionException("Bad request during identifier cache map update: status not 200");
        }
        list = all.getDocument();
        List<Node> objects = list.selectNodes(r.getServicesListPath());
        if (r.getServicesListPath().equals("roles_list/*")) {
            //XXX hack to deal with roles being inconsistent
            // XXX CSPACE-1887 workaround
            for (Node object : objects) {
                String csid = object.valueOf("@csid");
                out.add(csid);
            }

        } else {
            for (Node object : objects) {
                List<Node> fields = object.selectNodes("*");
                String csid = object.selectSingleNode("csid").getText();
                for (Node field : fields) {
                    if ("csid".equals(field.getName())) {
                        int idx = csid.lastIndexOf("/");
                        if (idx != -1)
                            csid = csid.substring(idx + 1);
                        out.add(csid);
                    } else if ("uri".equals(field.getName())) {
                        // Skip!
                    } 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, r.getServicesURL() + "/" + csid, json_name, value);
                        }
                    }
                }
            }
        }
        return out.toArray(new String[0]);
    } catch (ConnectionException e) {
        throw new UnderlyingStorageException("Service layer exception" + e.getLocalizedMessage(), e.getStatus(),
                e.getUrl(), e);
    } catch (UnsupportedEncodingException e) {
        throw new UnderlyingStorageException("Service layer exception:UnsupportedEncodingException", e);
    } catch (JSONException e) {
        throw new UnderlyingStorageException("Service layer exception:JSONException", e);
    }
}

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

License:Educational Community License

private boolean post_filter(CSPRequestCredentials creds, CSPRequestCache cache, JSONObject restrictions,
        Node candidate) throws ExistException, UnderlyingStorageException, ConnectionException, JSONException {
    if (restrictions == null)
        return true;
    // Subject/*from ww w. j ava 2 s.  c  om*/
    String src_csid = candidate.selectSingleNode("subjectCsid").getText();
    String rest_src = restrictions.optString("src");
    if (rest_src != null && !"".equals(rest_src)) {
        String[] data = rest_src.split("/");
        if (data[0].equals("")) {
            rest_src = rest_src.substring(1);
            data = rest_src.split("/");
        }
        if (!src_csid.equals(rest_src.split("/")[1]))
            return false;
    }
    String dst_csid = candidate.selectSingleNode("objectCsid").getText();
    String rest_dst = restrictions.optString("dst");
    if (rest_dst != null && !"".equals(rest_dst)) {
        String[] data2 = rest_dst.split("/");
        if (data2[0].equals("")) {
            rest_dst = rest_dst.substring(1);
            data2 = rest_dst.split("/");
        }
        if (!dst_csid.equals(rest_dst.split("/")[1]))
            return false;
    }
    // Retrieve the relation (CSPACE-1081)
    ReturnedMultipartDocument rel = conn.getMultipartXMLDocument(RequestMethod.GET,
            candidate.selectSingleNode("uri").getText(), null, creds, cache);
    if (rel.getStatus() == 404)
        throw new ExistException("Not found");
    Document rel_doc = rel.getDocument("relations_common");
    if (rel_doc == null)
        throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
    String type = rel_doc.selectSingleNode("relations_common/relationshipType").getText();
    if (restrictions.has("type") && !type.equals(restrictions.optString("type")))
        return false;
    return true;
}