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.ojbc.util.fedquery.processor.PrepareFederatedQueryMessage.java

Document removeSystemNamesNotIntendedForAdapter(Document requestMessage, String endpointUriValue) {

    //We need to clone the node because the recipient list message is mutable
    Document clonedRequestDocument = (Document) requestMessage.cloneNode(true);
    NodeList sourceSystems = clonedRequestDocument.getElementsByTagName("SourceSystemNameText");

    Set<Node> targetElementsToRemove = new HashSet<Node>();

    //Loop through the source systems and remove any source systems that don't match the system we are calling
    //We can't remove them from the live list so we put them in a set and remove later
    //http://stackoverflow.com/questions/1374088/removing-dom-nodes-when-traversing-a-nodelist
    for (int s = 0; s < sourceSystems.getLength(); s++) {

        Node sourceSystemNode = sourceSystems.item(s);

        if (sourceSystemNode.getNodeType() == Node.ELEMENT_NODE) {

            String currentSourceSystemNode = sourceSystemNode.getTextContent();

            if (!currentSourceSystemNode.equals(endpointUriValue)) {
                targetElementsToRemove.add(sourceSystemNode);
            }/*from w ww .ja  v a2  s  .  c  om*/
        }

    }

    for (Node e : targetElementsToRemove) {
        e.getParentNode().removeChild(e);
    }

    //Set the message body of the modified message
    return clonedRequestDocument;
}

From source file:org.omg.bpmn.miwg.util.xml.diff.AbstractXmlDifferenceListener.java

/**
 * Initializes the difference listener according to the configuration.
 * //from w w w .  java2s . c o  m
 * All XPath expressions are evaluated and the returned nodes stored for
 * later comparison. This is necessary, because the nodes accessible through
 * the XmlUnit API are not comparable to the actual document nodes. That comparison, however,
 * is necessary to resolve differences.
 * 
 * @param controlDoc
 * @param testDoc
 * @param configuration
 */
public void initialize(Document controlDoc, Document testDoc, XmlDiffConfiguration configuration) {
    LOGGER.trace("DifferenceListener Initialization started");

    ignoredNodes.clear();
    ignoredNodesParents.clear();
    idsAndIdRefs.clear();
    caseInsensitiveAttributes.clear();
    ignoredNamespacesInAttributes.clear();
    languageSpecificAttributes.clear();
    defaultAttributesMap.clear();
    ignoredAttributesMap.clear();
    optionalAttributesMap.clear();
    defaultAttributeValues.clear();

    numIgnoredDiffs = numAcceptedDiffs = 0;
    helper = new XmlUnitHelper(controlDoc, testDoc, configuration.getElementsPrefixMatcher());

    List<Node> tmpNodeList;

    // parse ignored attributes
    parseAttributes(configuration.getDefaultAttributes(), defaultAttributesMap);

    // parse ignored nodes
    for (String ignoredNodeXpath : configuration.getIgnoredNodes()) {
        tmpNodeList = helper.getAllMatchingNodesFromBothDocuments(ignoredNodeXpath);
        for (Node ignoredNode : tmpNodeList) {
            ignoredNodes.add(ignoredNode);
            ignoredNodesParents.add(ignoredNode.getParentNode());
        }
    }

    // parse ignored attributes
    parseAttributes(configuration.getIgnoredAttributes(), ignoredAttributesMap);

    // parse optional attributes
    parseAttributes(configuration.getIgnoredAttributes(), optionalAttributesMap);

    defaultAttributeValues.putAll(configuration.getDefaultAttributeValues());

    // parse case insensitive attributes
    for (String caseAttributeName : configuration.getCaseInsensitiveAttributeNames()) {
        this.caseInsensitiveAttributes.add(caseAttributeName);
    }

    // store names of id and id reference attributes
    for (String attrName : configuration.getIdsAndIdRefNames()) {
        this.idsAndIdRefs.add(attrName);
    }

    // ignored namespaces in attributes
    for (String ns : configuration.getIgnoredNamespacesInAttributes()) {
        this.ignoredNamespacesInAttributes.add(ns);
    }

    //language specific attributes
    for (String attrName : configuration.getLanguageSpecificAttributes()) {
        this.languageSpecificAttributes.add(attrName);
    }
    LOGGER.trace("DifferenceListener Initialization finished");
}

From source file:org.omg.bpmn.miwg.util.xml.diff.AbstractXmlDifferenceListener.java

/**
 * Ignores all differences caused by an ignored child node (see {@link DiffConfiguration#getIgnoredNodes()}
 * @param difference//from  w w  w  .  j a  v a2 s  . c  om
 * @return
 */
protected boolean isCausedByIgnoredChildNode(Difference difference) {
    switch (difference.getId()) {
    case DifferenceConstants.CHILD_NODELIST_LENGTH_ID:
    case DifferenceConstants.HAS_CHILD_NODES_ID:
        for (XmlDiffDocumentType type : XmlDiffDocumentType.values()) {
            Node node = helper.getDocumentNode(difference, type, false);
            if (node == null) {
                continue;
            }
            if (ignoredNodesParents.contains(node)) {
                return true;
            }
            if (findCorrespondingNode(ignoredNodesParents, node) != null) {
                return true;
            }
        }
        break;
    case DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID:
        for (XmlDiffDocumentType type : XmlDiffDocumentType.values()) {
            Node node = helper.getDocumentNode(difference, type, false);
            if (node == null) {
                continue;
            }
            if (ignoredNodesParents.contains(node.getParentNode())) {
                return true;
            }
            if (findCorrespondingNode(ignoredNodesParents, node.getParentNode()) != null) {
                return true;
            }
        }
        break;
    case DifferenceConstants.CHILD_NODE_NOT_FOUND_ID:
        Node node;
        if (difference.getControlNodeDetail().getNode() != null) {
            node = helper.getDocumentNode(difference, XmlDiffDocumentType.CONTROL, false);
        } else {
            node = helper.getDocumentNode(difference, XmlDiffDocumentType.TEST, false);
        }

        if (ignoredNodes.contains(node)) {
            return true;
        }
    }
    return false;
}

From source file:org.omg.bpmn.miwg.util.xml.diff.AbstractXmlDifferenceListener.java

/**
 * Ignores all differences within an ignored node (see {@link DiffConfiguration#getIgnoredNodes()}
 * @param difference//from w  w w.  java2s . co m
 * @return
 */
protected boolean isInIgnoredNode(Difference difference) {
    Node controlNode = helper.getDocumentNode(difference, XmlDiffDocumentType.CONTROL, false);

    if (controlNode == null) {
        return false;
    } else {
        Node current = controlNode;
        while (current != null) {
            if (ignoredNodes.contains(current)) {
                return true;
            }
            // else, try to find a node thats equal to current
            if (findCorrespondingNode(ignoredNodes, current) != null) {
                return true;
            }
            // if no equal node found continue with parent
            if (current instanceof Attr) {
                current = ((Attr) current).getOwnerElement();
            } else {
                current = current.getParentNode();
            }
        }
    }
    return false;

    // add same test for testNode if blacklisted nodes are not ignored
}

From source file:org.omg.bpmn.miwg.util.xml.XPathUtil.java

/**
 * Builds an absolute XPath string from the given node.
 * //from  w w w.  ja v a 2 s  . com
 * @param node
 * @param context namespace context used to determine correct namespace prefixes, see
 *            {@link SignavioNamespaceContext}
 * @return an XPath string or null (if no node was given)
 */
public static String getXPathString(Node node, NamespaceContext context) {
    if (node == null) {
        return null;
    }

    LinkedList<String> xpathSteps = new LinkedList<String>();
    String string = getNodeString(node, context);
    xpathSteps.add(string);
    Node current;
    if (node instanceof Attr)
        current = ((Attr) node).getOwnerElement();
    else
        current = node.getParentNode();

    while (current != node.getOwnerDocument()) {
        xpathSteps.add(getNodeString(current, context));
        current = current.getParentNode();
    }

    StringBuffer buff = new StringBuffer();
    Iterator<String> it = xpathSteps.descendingIterator();
    while (it.hasNext()) {
        buff.append("/" + it.next());
    }
    return buff.toString();
}

From source file:org.opendaylight.aaa.cert.impl.CertificateManagerService.java

private void updateCertManagerSrvConfig(String ctlPwd, String trustPwd) {
    try {//from  ww w  .  j av  a  2 s.  c o  m
        LOG.debug("Update Certificate manager service config file");
        final File configFile = new File(DEFAULT_CONFIG_FILE_PATH);
        if (configFile.exists()) {
            final String storePwdTag = "store-password";
            final String ctlStoreTag = "ctlKeystore";
            final String trustStoreTag = "trustKeystore";
            final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            final DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            final Document doc = docBuilder.parse(configFile);
            final NodeList ndList = doc.getElementsByTagName(storePwdTag);
            for (int i = 0; i < ndList.getLength(); i++) {
                final Node nd = ndList.item(i);
                if (nd.getParentNode() != null && nd.getParentNode().getNodeName().equals(ctlStoreTag)) {
                    nd.setTextContent(ctlPwd);
                } else if (nd.getParentNode() != null
                        && nd.getParentNode().getNodeName().equals(trustStoreTag)) {
                    nd.setTextContent(trustPwd);
                }
            }
            final TransformerFactory transformerFactory = TransformerFactory.newInstance();
            final Transformer transformer = transformerFactory.newTransformer();
            final DOMSource source = new DOMSource(doc);
            final StreamResult result = new StreamResult(new File(DEFAULT_CONFIG_FILE_PATH));
            transformer.transform(source, result);
        } else {
            LOG.warn("The Certificate manager service config file does not exist {}", DEFAULT_CONFIG_FILE_PATH);
        }
    } catch (ParserConfigurationException | TransformerException | SAXException | IOException e) {
        LOG.error("Error while updating Certificate manager service config file", e);
    }
}

From source file:org.openengsb.openengsbplugin.tools.Tools.java

/**
 * Remove node with given {@code xpath} from {@code targetDocument}. When {@code removeParent} is set to
 * {@code true} the parent node will also be removed if the removed node was the only child. The method returns
 * {@code true} if the node specified by {@code xpath} has been found and successfully removed from its parent node.
 *//*from   w w  w  .  ja va  2 s .c o  m*/
public static boolean removeNode(String xpath, Document targetDocument, NamespaceContext nsContext,
        boolean removeParent) throws XPathExpressionException {
    Node nodeToRemove = evaluateXPath(xpath, targetDocument, nsContext, XPathConstants.NODE, Node.class);
    if (nodeToRemove == null) {
        return false;
    }
    Node parent = nodeToRemove.getParentNode();
    if (parent == null) {
        return false;
    }
    parent.removeChild(nodeToRemove);
    if (removeParent && parent.getChildNodes().getLength() == 0) {
        Node parentParent = parent.getParentNode();
        if (parentParent != null) {
            parentParent.removeChild(parent);
        }
    }
    return true;
}

From source file:org.openestate.io.openimmo.converters.OpenImmo_1_2_1.java

/**
 * Downgrade &lt;energiepass&gt; elements to OpenImmo 1.2.0.
 * <p>/*from   w  w  w  .  ja v a  2s.  co  m*/
 * The &lt;mitwarmwasser&gt; child element of the &lt;energiepass&gt; element
 * is not available in version 1.2.0.
 * <p>
 * The &lt;energieverbrauchkennwert&gt;, &lt;endenergiebedarf&gt; child
 * elements of the &lt;energiepass&gt; element are moved into
 * &lt;energiebedarf&gt; and &lt;skala&gt; in version 1.2.0.
 *
 * @param doc OpenImmo document in version 1.2.1
 * @throws JaxenException
 */
protected void downgradeEnergiepassElements(Document doc) throws JaxenException {
    List nodes = XmlUtils
            .newXPath("/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass", doc)
            .selectNodes(doc);
    for (Object item : nodes) {
        Element parentNode = (Element) item;
        boolean skalaProcessed = false;
        String artValue = XmlUtils.newXPath("io:art/text()", doc).stringValueOf(parentNode);

        List childNodes = XmlUtils.newXPath("io:mitwarmwasser", doc).selectNodes(parentNode);
        for (Object child : childNodes) {
            Node childNode = (Node) child;
            childNode.getParentNode().removeChild(childNode);
        }

        childNodes = XmlUtils.newXPath("io:energieverbrauchkennwert", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node childNode = (Node) childItem;
            String childValue = StringUtils.trimToNull(childNode.getTextContent());
            if (!skalaProcessed && "VERBRAUCH".equalsIgnoreCase(artValue) && childValue != null) {
                skalaProcessed = true;
                Element skalaNode = doc.createElementNS(OpenImmoUtils.OLD_NAMESPACE, "skala");
                skalaNode.setAttribute("type", "ZAHL");
                skalaNode.setTextContent(childValue);
                parentNode.appendChild(skalaNode);
            }
            childNode.getParentNode().removeChild(childNode);
        }

        childNodes = XmlUtils.newXPath("io:endenergiebedarf", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node childNode = (Node) childItem;
            String childValue = StringUtils.trimToNull(childNode.getTextContent());
            if (!skalaProcessed && "BEDARF".equalsIgnoreCase(artValue) && childValue != null) {
                skalaProcessed = true;
                Element skalaNode = doc.createElementNS(OpenImmoUtils.OLD_NAMESPACE, "skala");
                skalaNode.setAttribute("type", "ZAHL");
                skalaNode.setTextContent(childValue);
                parentNode.appendChild(skalaNode);

                Element newNode = doc.createElementNS(OpenImmoUtils.OLD_NAMESPACE, "energiebedarf");
                newNode.setTextContent(childValue);
                parentNode.appendChild(newNode);
            }
            childNode.getParentNode().removeChild(childNode);
        }
    }
}

From source file:org.openestate.io.openimmo.converters.OpenImmo_1_2_1.java

/**
 * Upgrade &lt;energiepass&gt; elements to OpenImmo 1.2.1.
 * <p>//w  w w  .j av  a  2s  .  co m
 * Make sure, that a valid value for &lt;art&gt; is used.
 * <p>
 * Remove unsupported &lt;heizwert&gt; element.
 * <p>
 * Replace &lt;energiebedarf&gt;, &lt;skala&gt; with
 * &lt;energieverbrauchkennwert&gt; or &lt;endenergiebedarf&gt; according to
 * the provided &lt;art&gt;.
 *
 * @param doc OpenImmo document in version 1.2.0
 * @throws JaxenException
 */
protected void upgradeEnergiepassElements(Document doc) throws JaxenException {
    List nodes = XmlUtils
            .newXPath("/io:openimmo/io:anbieter/io:immobilie/io:zustand_angaben/io:energiepass", doc)
            .selectNodes(doc);
    for (Object item : nodes) {
        Element parentNode = (Element) item;
        String energiebedarfValue = null;
        String skalaValue = null;

        Element artNode = (Element) XmlUtils.newXPath("io:art", doc).selectSingleNode(parentNode);
        String artValue = (artNode != null) ? StringUtils.trimToNull(artNode.getTextContent()) : null;

        List childNodes = XmlUtils.newXPath("io:heizwert", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node childNode = (Node) childItem;
            childNode.getParentNode().removeChild(childNode);
        }

        childNodes = XmlUtils.newXPath("io:energiebedarf", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Node childNode = (Node) childItem;
            if (energiebedarfValue == null)
                energiebedarfValue = StringUtils.trimToNull(childNode.getTextContent());
            childNode.getParentNode().removeChild(childNode);
        }

        childNodes = XmlUtils.newXPath("io:skala", doc).selectNodes(parentNode);
        for (Object childItem : childNodes) {
            Element childNode = (Element) childItem;
            if (skalaValue == null && "ZAHL".equalsIgnoreCase(childNode.getAttribute("type")))
                skalaValue = StringUtils.trimToNull(childNode.getTextContent());
            childNode.getParentNode().removeChild(childNode);
        }

        if (artNode != null && "VERBRAUCH".equalsIgnoreCase(artValue)) {
            artNode.setTextContent("VERBRAUCH");
            String value = skalaValue;
            if (value != null) {
                Element newNode = doc.createElementNS(StringUtils.EMPTY, "energieverbrauchkennwert");
                newNode.setTextContent(value);
                parentNode.appendChild(newNode);
            }
        } else if (artNode != null && "BEDARF".equalsIgnoreCase(artValue)) {
            artNode.setTextContent("BEDARF");
            String value = (energiebedarfValue != null) ? energiebedarfValue : skalaValue;
            if (value != null) {
                Element newNode = doc.createElementNS(StringUtils.EMPTY, "endenergiebedarf");
                newNode.setTextContent(value);
                parentNode.appendChild(newNode);
            }
        }
    }
}

From source file:org.opennaas.extensions.router.model.utils.OpticalSwitchTopologyLoader.java

private String getPortNodeName(Node port) {
    if (port != null) {
        // port -> ports -> slot -> chassis -> node
        Node portNode = port.getParentNode().getParentNode().getParentNode().getParentNode();
        if (portNode.getNodeType() == Node.ELEMENT_NODE) {
            return portNode.getAttributes().getNamedItem("id").getTextContent();
        }// w  w w  . jav a2s  .c  om
    }
    return "";
}