Example usage for org.w3c.dom Node getParentNode

List of usage examples for org.w3c.dom Node getParentNode

Introduction

In this page you can find the example usage for org.w3c.dom Node getParentNode.

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

From source file:org.sakaiproject.archive.impl.BasicArchiveService.java

/**
* Merge the the permission-roles settings into the site
* @param element The XML DOM tree of messages to merge.
* @param siteId The id of the site getting imported into.
*///w ww .j av a  2s.  c  o m
protected void mergeSiteRoles(Element el, String siteId, HashMap useIdTrans) throws PermissionException {
    // heck security (throws if not permitted)
    unlock(SiteService.SECURE_UPDATE_SITE, SiteService.siteReference(siteId));

    String source = "";

    // el: <roles> node         
    Node parent0 = el.getParentNode(); // parent0: <site> node
    Node parent1 = parent0.getParentNode(); // parent1: <service> node
    Node parent = parent1.getParentNode(); // parent: <archive> node containing "system"

    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    List roles = new Vector();
    // to add this user with this role inito this realm
    String realmId = "/site/" + siteId;
    try {
        //AuthzGroup realmEdit = AuthzGroupService.getRealm(realmId);
        AuthzGroup realm = AuthzGroupService.getAuthzGroup(realmId);

        //roles.addAll(realmEdit.getRoles());
        roles.addAll(realm.getRoles());

        NodeList children = el.getChildNodes();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element element2 = (Element) child;

            if (source.equalsIgnoreCase(FROM_WT)) {
                // from WT, merge the users with roles into the new site

                NodeList children2 = element2.getChildNodes();
                final int length2 = children2.getLength();
                for (int i2 = 0; i2 < length2; i2++) {
                    Node child2 = children2.item(i2);
                    if (child2.getNodeType() != Node.ELEMENT_NODE)
                        continue;
                    Element element3 = (Element) child2;
                    if (!element3.getTagName().equals("ability"))
                        continue;

                    String userId = element3.getAttribute("userId");

                    // under 2 conditions the userIdTrans would be empty
                    // 1st is, even from WT, no user id has been processed
                    // 2nd is, this user is not from WT. userIdTrans is always empty
                    if (!userIdTrans.isEmpty()) {
                        // user the new id if the old one from WT has been replaced
                        String newId = (String) useIdTrans.get(userId);
                        if (newId != null)
                            userId = newId;
                    }
                    try {
                        User user = UserDirectoryService.getUser(userId);
                        String roleId = element3.getAttribute("roleId");
                        //Role role = realmEdit.getRole(roleId);
                        Role role = realm.getRole(roleId);
                        if (role != null) {
                            AuthzGroup realmEdit = AuthzGroupService.getAuthzGroup(realmId);
                            realmEdit.addMember(user.getId(), role.getId(), true, false);
                            AuthzGroupService.save(realmEdit);
                        }
                    } catch (UserNotDefinedException e) {
                        M_log.warn("UserNotDefined in mergeSiteRoles: " + userId);
                    } catch (AuthzPermissionException e) {
                        M_log.warn("AuthzPermissionException in mergeSiteRoles", e);
                    }
                }
            } else {
                // for both CT classic and Sakai CTools

                // check is this roleId is a qualified one
                if (!checkSystemRole(source, element2.getTagName()))
                    continue;

                NodeList children2 = element2.getChildNodes();
                final int length2 = children2.getLength();
                for (int i2 = 0; i2 < length2; i2++) {
                    Node child2 = children2.item(i2);
                    if (child2.getNodeType() != Node.ELEMENT_NODE)
                        continue;
                    Element element3 = (Element) child2;
                    if (!element3.getTagName().equals("ability"))
                        continue;

                    String userId = element3.getAttribute("userId");

                    // this user has a qualified role, his/her resource will be imported
                    usersListAllowImport.add(userId);
                }
            } // if - elseif - elseif
        } // for
    } catch (GroupNotDefinedException err) {
        M_log.warn("()mergeSiteRoles realm edit exception caught GroupNotDefinedException " + realmId);
    }
    return;

}

From source file:org.sakaiproject.archive.impl.SiteMerger.java

/**
* Merge the the permission-roles settings into the site
* @param element The XML DOM tree of messages to merge.
* @param siteId The id of the site getting imported into.
*///  www.j  av a  2 s . c  o  m
protected void mergeSiteRoles(Element el, String siteId, HashMap useIdTrans, boolean filterSakaiRoles,
        String[] filteredSakaiRoles) throws PermissionException {
    // heck security (throws if not permitted)
    unlock(SiteService.SECURE_UPDATE_SITE, m_siteService.siteReference(siteId));

    String source = "";

    // el: <roles> node         
    Node parent0 = el.getParentNode(); // parent0: <site> node
    Node parent1 = parent0.getParentNode(); // parent1: <service> node
    Node parent = parent1.getParentNode(); // parent: <archive> node containing "system"

    if (parent.getNodeType() == Node.ELEMENT_NODE) {
        Element parentEl = (Element) parent;
        source = parentEl.getAttribute("system");
    }

    List roles = new Vector();
    //List maintainUsers = new Vector();
    //List accessUsers = new Vector();

    // to add this user with this role inito this realm
    String realmId = m_siteService.siteReference(siteId); //SWG "/site/" + siteId;
    try {
        AuthzGroup realm = m_authzGroupService.getAuthzGroup(realmId);
        roles.addAll(realm.getRoles());

        NodeList children = el.getChildNodes();
        final int length = children.getLength();
        for (int i = 0; i < length; i++) {
            Node child = children.item(i);
            if (child.getNodeType() != Node.ELEMENT_NODE)
                continue;
            Element element2 = (Element) child;
            String roleId = null;

            if (ArchiveService.FROM_SAKAI_2_8.equals(source)) {
                if (!"role".equals(element2.getTagName()))
                    continue;

                roleId = element2.getAttribute("roleId");
            } else {
                roleId = element2.getTagName();
            }

            //SWG Getting rid of WT part above, this was previously the else branch labeled "for both CT classic and Sakai CTools"
            // check is this roleId is a qualified one
            if (!checkSystemRole(source, roleId, filterSakaiRoles, filteredSakaiRoles))
                continue;

            NodeList children2 = element2.getChildNodes();
            final int length2 = children2.getLength();
            for (int i2 = 0; i2 < length2; i2++) {
                Node child2 = children2.item(i2);
                if (child2.getNodeType() != Node.ELEMENT_NODE)
                    continue;
                Element element3 = (Element) child2;
                if (!element3.getTagName().equals("ability"))
                    continue;

                String userId = element3.getAttribute("userId");
                // this user has a qualified role, his/her resource will be imported
                usersListAllowImport.add(userId);
            }
        } // for
    } catch (Exception err) {
        M_log.warn("()mergeSiteRoles realm edit exception caught" + realmId, err);
    }
    return;

}

From source file:org.sakaiproject.james.JamesServlet.java

protected void customizeConfig(String host, String dns1, String dns2, String smtpPort, String logDir,
        String postmasterAddress) throws JamesConfigurationException {
    String configPath = m_phoenixHome + "/apps/james/SAR-INF/config.xml";
    String environmentPath = m_phoenixHome + "/apps/james/SAR-INF/environment.xml";

    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc;//from   w w w.  jav a 2 s . c  o  m

    try {
        // process config.xml first
        doc = Xml.readDocument(configPath);
        if (doc == null) {
            M_log.error("init(): James config file " + configPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        if (postmasterAddress == null) {
            postmasterAddress = "postmaster@" + host;
        }

        // build a hashmap of node paths and values to set
        HashMap<String, String> nodeValues = new HashMap<String, String>();

        // WARNING!! in XPath, node-set indexes begin with 1, and NOT 0
        nodeValues.put("/config/James/servernames/servername[1]", host);
        nodeValues.put("/config/dnsserver/servers/server[2]", dns1);
        nodeValues.put("/config/dnsserver/servers/server[3]", dns2);
        nodeValues.put("/config/James/postmaster", postmasterAddress);
        nodeValues.put("/config/smtpserver/port", smtpPort);

        // loop through the hashmap, setting each value, or failing if one can't be found
        for (String nodePath : nodeValues.keySet()) {
            if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
                if (nodePath.startsWith("/config/dnsserver/servers/server")) {
                    // add node (only if we're dealing with DNS server entries)
                    Element element = doc.createElement("server");
                    element.appendChild(doc.createTextNode(nodeValues.get(nodePath)));
                    Node parentNode = (Node) xpath.evaluate("/config/dnsserver/servers", doc,
                            XPathConstants.NODE);
                    parentNode.appendChild(element);

                } else {
                    // else, throw an exception
                    throw new JamesConfigurationException();
                }

            } else {
                // change existing node (if value != null else remove it)
                Node node = (Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE);
                if (nodeValues.get(nodePath) != null) {
                    node.setTextContent(nodeValues.get(nodePath));
                } else {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        M_log.debug("init(): writing James configuration to " + configPath);
        Xml.writeDocument(doc, configPath);

        // now handle environment.xml
        doc = Xml.readDocument(environmentPath);
        if (doc == null) {
            M_log.error("init(): James config file " + environmentPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        String nodePath = "/server/logs/targets/file/filename";
        String nodeValue = logDir + "james";

        if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
            M_log.error("init(): Could not find XPath '" + nodePath + "' in " + environmentPath + ".");
            throw new JamesConfigurationException();
        }
        ((Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE)).setTextContent(nodeValue);

        M_log.debug("init(): writing James configuration to " + environmentPath);
        Xml.writeDocument(doc, environmentPath);
    } catch (JamesConfigurationException e) {
        throw e;
    } catch (Exception e) {
        M_log.warn("init(): An unhandled exception was encountered while configuring James: " + e.getMessage());
    }
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlStringBuffer.java

/**
 * remove element/*from w w  w . j  a  v  a2  s .  co  m*/
 *
 * @param xpath
 */
public final void removeElement(String xpath) {
    if (log.isDebugEnabled()) {
        log.debug("removeElement(String " + xpath + ")");
    }

    List nodes = this.selectNodes(xpath);
    Iterator iterator = nodes.iterator();
    while (iterator.hasNext()) {
        Node node = (Node) iterator.next();
        Node parent = node.getParentNode();
        parent.removeChild(node);
    }
}

From source file:org.sejda.conversion.PdfFileSourceListAdapter.java

/**
 * Parse fileset definitions <filelist><fileset>[...]</fileset></filelist> ignoring the rest of the document
 * //  w w w  . j  a  v  a  2 s  .  co  m
 * @param doc
 * @return a list of string matching the contents of the <filelist><fileset> tags in the document
 * @throws XPathExpressionException
 */
private List<String> parseFileSets(Document doc, File configFile) throws XPathExpressionException {
    List<String> result = new ArrayList<>();

    NodeList nodeList = getNodeListMatchingXpath("//filelist/fileset/file", doc);
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Node fileSet = node.getParentNode();

        String parentDirPath = nullSafeGetStringAttribute(fileSet, "dir");
        if (parentDirPath == null) {
            parentDirPath = configFile.getAbsoluteFile().getParent();
        }

        String filePath = extractFilePath(node);

        // warn if file in fileset is using absolute path mode
        if (FilenameUtils.getPrefixLength(filePath) > 0) {
            LOG.warn("File " + filePath + " in fileset "
                    + StringUtils.defaultIfBlank(nullSafeGetStringAttribute(fileSet, "dir"), "")
                    + " seems to be an absolute path. Will _not_ be resolved relative to the <fileset>, but as an absolute path. Normally you would want to use relative paths in a //filelist/fileset/file, and absolute paths in a //filelist/file.");
        }

        result.add(FilenameUtils.concat(parentDirPath, filePath));
    }

    return result;
}

From source file:org.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *//*www  .  j a va  2 s  .  c  o m*/
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        displayMessageln("\t" + parameter.getKey() + " (mode:" + parameter.getMode() + ")");
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            ((Element) newNode).setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.silverpeas.util.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 *
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *///w  w  w  .  j a v  a  2  s . com
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        console.printMessage('\t' + parameter.getKey() + " (mode:" + parameter.getMode() + ')');
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            newNode.setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.slc.sli.scaffold.DocumentManipulator.java

private Document addDefaultDocs(Document doc) throws XPathExpressionException {
    XPath xPath = XPathFactory.newInstance().newXPath();
    xPath.setNamespaceContext(new MyNameSpaceContext());
    XPathExpression exp = xPath.compile("//method[not(doc)]");
    NodeList nl = (NodeList) exp.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < nl.getLength(); i++) {
        Node item = nl.item(i);
        String id = item.getAttributes().getNamedItem("id").getNodeValue();
        Node docElem = doc.createElement("doc");
        String defaultDoc = null;
        if ("readAll".equals(id)) {
            defaultDoc = "Returns the requested collection of resource representations.";
        } else if ("read".equals(id)) {
            defaultDoc = "Returns the specified resource representation(s).";
        } else if ("create".equals(id)) {
            defaultDoc = "Creates a new resource using the given resource data.";
        } else if ("delete".equals(id)) {
            defaultDoc = "Deletes the specified resource.";
        } else if ("update".equals(id)) {
            defaultDoc = "Updates the specified resource using the given resource data.";
        }// w  w w .  j av a  2s .  com
        if (defaultDoc != null) {
            Text text = doc.createTextNode(defaultDoc);
            docElem.appendChild(text);
            item.appendChild(docElem);
        }
    }

    // "//ns2:param[@name='id']"
    XPathExpression idDelExp = xPath
            .compile("//param[contains(@name, 'id') or contains(@name, 'Id')][@style='template']/doc");
    NodeList idDelNl = (NodeList) idDelExp.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < idDelNl.getLength(); i++) {
        Node item = idDelNl.item(i);
        item.getParentNode().removeChild(item);
    }

    // "//ns2:param[@name='id']"
    XPathExpression idExp = xPath
            .compile("//param[contains(@name, 'id') or contains(@name, 'Id')][@style='template'][not(doc)]");
    NodeList idNl = (NodeList) idExp.evaluate(doc, XPathConstants.NODESET);
    for (int i = 0; i < idNl.getLength(); i++) {
        Node item = idNl.item(i);
        Node docElem = doc.createElement("doc");
        String defaultDoc = "A comma-separated list of resource IDs.";
        if (defaultDoc != null) {
            Text text = doc.createTextNode(defaultDoc);
            docElem.appendChild(text);
            item.appendChild(docElem);
        }
    }

    return doc;
}

From source file:org.slc.sli.scaffold.ResourceDocumentation.java

private String getPath(final Node node) {
    final Node pathNode = node.getAttributes().getNamedItem("path");
    if (pathNode != null) {
        String parentPath = getPath(node.getParentNode());
        String nodePath = pathNode.getNodeValue();
        return parentPath.isEmpty() ? nodePath : parentPath + "/" + nodePath;
    } else {/* w  ww .  j a va 2 s . c  o  m*/
        return "";
    }
}

From source file:org.sonar.plugins.xml.checks.IndentCheck.java

/**
 * Get the depth of this node in the node hierarchy.
 *//*from   w w w  . j  a  v  a 2 s  .c  o  m*/
private int getDepth(Node node) {
    int depth = 0;
    for (Node parent = node.getParentNode(); parent.getParentNode() != null; parent = parent.getParentNode()) {
        depth++;
    }
    return depth;
}