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:jef.tools.XMLUtils.java

/**
 * ???tagNameElement/*  w ww .  j  av a2 s. c om*/
 * 
 * @param node
 *            
 * @param tagName
 *            ?????
 * @return ?
 */
public static Element firstParent(Node node, String tagName) {
    if (StringUtils.isEmpty(tagName))
        return (Element) node.getParentNode();
    Node p = node.getParentNode();
    while (p != null) {
        if (p.getNodeType() == Node.ELEMENT_NODE && p.getNodeName().equals(tagName)) {
            return (Element) p;
        }
        p = p.getParentNode();
    }
    return null;
}

From source file:com.gargoylesoftware.htmlunit.html.DomNode.java

/**
 * {@inheritDoc}//w  w  w. ja  v  a2  s  . c  o  m
 */
public Node insertBefore(final Node newChild, final Node refChild) {
    if (refChild == null) {
        appendChild(newChild);
    } else {
        if (refChild.getParentNode() != this) {
            throw new DOMException(DOMException.NOT_FOUND_ERR, "Reference node is not a child of this node.");
        }
        ((DomNode) refChild).insertBefore((DomNode) newChild);
    }
    return null;
}

From source file:cz.muni.fi.mir.mathmlunificator.MathMLUnificator.java

/**
 * <p>//from   w  w  w.  j a  va  2s .c  om
 * Implementation of MathML unification. In the given W3C DOM represented
 * XML document find all maths nodes (see
 * {@link DocumentParser#findMathMLNodes(org.w3c.dom.Document)}) and
 * remember links to operator elements and other elements in
 * {@link #nodesByDepth} data structure. Then substitute them gradualy for
 * series of formulae with leaf elements substituted for a special
 * unification representing symbol {@code &#x25CD;} (for Presentation
 * MathML, see {@link Constants#PMATHML_UNIFICATOR}) or {@code &#x25D0;}
 * (for Content MathML, see {@link Constants#CMATHML_UNIFICATOR}).
 * </p>
 * <p>
 * Resulting series of the original and unified MathML nodes is itself
 * encapsulated in a new element &lt;unified-math&gt; (see
 * {@link Constants#UNIFIED_MATHML_ROOT_ELEM}) in XML namespace
 * <code>http://mir.fi.muni.cz/mathml-unification/</code> (see
 * {@link Constants#UNIFIED_MATHML_NS}) and put to the place of the original
 * math element {@link Node} in the XML DOM representation the node is
 * attached to.
 * </p>
 *
 * @param mathNode W3C DOM XML document representation attached MathML node
 * to work on.
 * @param workInPlace If <code>true</code>, given <code>mathNode</code> will
 * be modified in place; if <code>false</code>, <code>mathNode</code> will
 * not be modified and series of modified nodes will be returned.
 * @param operatorUnification If <code>true</code> unify also operator
 * nodes, otherwise keep operator nodes intact.
 * @return <code>null</code> if <code>workInPlace</code> is
 * <code>false</code>; otherwise collection of unified versions of the
 * <code>mathNode</code> with key of the {@link HashMap} describing order
 * (level of unification) of elements in the collection.
 */
private HashMap<Integer, Node> unifyMathMLNodeImpl(Node mathNode, boolean operatorUnification,
        boolean workInPlace) {

    if (mathNode.getOwnerDocument() == null) {
        String msg = "The given node is not attached to any document.";
        if (mathNode.getNodeType() == Node.DOCUMENT_NODE) {
            msg = "The given node is document itself. Call with mathNode.getDocumentElement() instead.";
        }
        throw new IllegalArgumentException(msg);
    }

    nodesByDepth = new HashMap<>();

    Node unifiedMathNode = null;
    HashMap<Integer, Node> unifiedNodesList = null;
    Document unifiedMathDoc = null;

    if (workInPlace) {
        // New element encapsulating the series of unified formulae.
        unifiedMathNode = mathNode.getOwnerDocument().createElementNS(UNIFIED_MATHML_NS,
                UNIFIED_MATHML_ROOT_ELEM);
        mathNode.getParentNode().replaceChild(unifiedMathNode, mathNode);
        unifiedMathNode.appendChild(mathNode.cloneNode(true));
    } else {
        unifiedNodesList = new HashMap<>();
        // Create a new separate DOM to work over with imporeted clone of the node given by user
        unifiedMathDoc = DOMBuilder.createNewDocWithNodeClone(mathNode, true);
        mathNode = unifiedMathDoc.getDocumentElement();
    }

    // Parse XML subtree starting at mathNode and remember elements by their depth.
    rememberLevelsOfNodes(mathNode, operatorUnification);

    // Build series of formulae of level by level unified MathML.
    NodeLevel<Integer, Integer> level = new NodeLevel<>(getMaxMajorNodesLevel(), NUMOFMINORLEVELS);
    int levelAttrCounter = 0;
    Collection<Attr> maxLevelAttrs = new LinkedList<>();
    while (level.major > 0) {
        if (nodesByDepth.containsKey(level)) {
            if (unifyAtLevel(level)) {
                levelAttrCounter++;

                Node thisLevelMathNode = mathNode.cloneNode(true);
                Attr thisLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_LEVEL_ATTR);
                Attr maxLevelAttr = thisLevelMathNode.getOwnerDocument().createAttributeNS(UNIFIED_MATHML_NS,
                        UNIFIED_MATHML_NS_PREFIX + ":" + UNIFIED_MATHML_MAX_LEVEL_ATTR);
                maxLevelAttrs.add(maxLevelAttr);

                thisLevelAttr.setTextContent(String.valueOf(levelAttrCounter));

                ((Element) thisLevelMathNode).setAttributeNodeNS(thisLevelAttr);
                ((Element) thisLevelMathNode).setAttributeNodeNS(maxLevelAttr);

                if (workInPlace) {
                    unifiedMathNode.appendChild(thisLevelMathNode);
                } else {
                    // Create a new document for every node in the collection.
                    unifiedNodesList.put(levelAttrCounter,
                            DOMBuilder.cloneNodeToNewDoc(thisLevelMathNode, true));
                }
            }
        }
        level.minor--;
        if (level.minor <= 0) {
            level.major--;
            level.minor = NUMOFMINORLEVELS;
        }
    }
    for (Attr attr : maxLevelAttrs) {
        attr.setTextContent(String.valueOf((levelAttrCounter)));
    }

    if (workInPlace) {
        return null;
    } else {
        for (Node node : unifiedNodesList.values()) {
            Attr maxLevelAttr = (Attr) node.getAttributes().getNamedItemNS(UNIFIED_MATHML_NS,
                    UNIFIED_MATHML_MAX_LEVEL_ATTR);
            if (maxLevelAttr != null) {
                maxLevelAttr.setTextContent(String.valueOf((levelAttrCounter)));
            }
        }
        return unifiedNodesList;
    }

}

From source file:jef.tools.XMLUtils.java

/**
 * //from w  ww  .  j  ava2  s . com
 * 
 * @param node
 *            ?
 * @param text
 *            
 * @param searchAttribute
 *            ?
 */
public static void removeNodeWithKeyword(Node node, String text, boolean searchAttribute) {
    String value = getValue(node);
    if (value != null && value.indexOf(text) > -1) {
        node.getParentNode().removeChild(node);
        return;
    }

    if (searchAttribute && node.getAttributes() != null) {
        for (Node n : toArray(node.getAttributes())) {
            value = getValue(n);
            if (value != null && value.indexOf(text) > -1) {
                node.getParentNode().removeChild(node);
                return;
            }
        }
    }
    for (Node sub : toArray(node.getChildNodes())) {
        removeNodeWithKeyword(sub, text, searchAttribute);
    }
}

From source file:Main.java

/**
 * Copies the source tree into the specified place in a destination
 * tree. The source node and its children are appended as children
 * of the destination node.//  w w w .j a  v  a  2s.c o m
 * <p>
 * <em>Note:</em> This is an iterative implementation.
 */
public static void copyInto(Node src, Node dest) throws DOMException {

    // get node factory
    Document factory = dest.getOwnerDocument();
    boolean domimpl = factory instanceof DocumentImpl;

    // placement variables
    Node start = src;
    Node parent = src;
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
                if (domimpl && !attr.getSpecified()) {
                    ((AttrImpl) element.getAttributeNode(attrName)).setSpecified(false);
                }
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + node.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        }

        // advance
        else {
            place = place.getNextSibling();
            while (place == null && parent != start) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

private void convertToXML(ZipFile logArchive, TcLogInfo logInfo, XMLStreamWriter writer)
        throws ParsingException, XMLStreamException {
    writer.writeStartDocument("utf-8", "1.0");

    Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive, DESCRIPTION_ENTRY_NAME);
    if (descriptionTopLevelNode == null) {
        throw new ParsingException("Unable to obtain description top-level node.");
    }/*from   w w  w . j a  va2  s . com*/

    Node topLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
            NodeUtils.getTextProperty(descriptionTopLevelNode, "root file name"));

    if (topLevelNode == null) {
        throw new ParsingException("Unable to obtain root top-level node.");
    }

    NodeList rootNodes = topLevelNode.getChildNodes();
    Node rootOwnerNode = NodeUtils.findRootOwnerNode(rootNodes);

    if (rootOwnerNode == null) {
        throw new ParsingException("Unable to obtain root owner node.");
    }

    boolean isSuite = "{00000000-0000-0000-0000-000000000000}"
            .equals(NodeUtils.getTextProperty(rootOwnerNode, "projectkey"));

    Node rootOwnerNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
            NodeUtils.getTextProperty(rootOwnerNode, "filename"));

    if (rootOwnerNodeInfo == null) {
        throw new ParsingException("Unable to obtain root owner node info.");
    }

    Node rootOwnerNodeInfoSummary = NodeUtils.findNamedNode(rootOwnerNodeInfo.getChildNodes(), "summary");
    boolean isSuiteOrProject = rootOwnerNodeInfoSummary != null;

    writer.writeStartElement("testsuites");

    if (isSuite) {
        List<Node> projects = NodeUtils.findChildNodes(rootOwnerNode,
                rootOwnerNode.getParentNode().getChildNodes());
        for (Node projectNode : projects) {
            Node projectNodeInfo = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                    NodeUtils.getTextProperty(projectNode, "filename"));
            Node projectNodeInfoSummary = NodeUtils.findNamedNode(projectNodeInfo, "summary");
            processProject(logArchive, projectNode, projectNodeInfoSummary, writer);
        }
    } else if (isSuiteOrProject) {
        processProject(logArchive, rootOwnerNode, rootOwnerNodeInfoSummary, writer);
    } else {
        String testCaseName = NodeUtils.getTextProperty(rootOwnerNode, "name");
        String testCaseDuration = Double.toString(logInfo.getTestDuration() / 1000f);

        writer.writeStartElement("testsuite");
        writer.writeAttribute("name", project);
        writer.writeAttribute("time", testCaseDuration);

        writer.writeStartElement("testcase");
        writer.writeAttribute("name", fixTestCaseName(testCaseName));
        writer.writeAttribute("classname", suite + "." + project);
        writer.writeAttribute("time", testCaseDuration);
        if (checkFail(NodeUtils.getTextProperty(rootOwnerNode, "status"))) {
            writer.writeStartElement("failure");

            List<String> messages = NodeUtils.getErrorMessages(rootOwnerNodeInfo);
            if (errorOnWarnings) {
                messages.addAll(NodeUtils.getWarningMessages(rootOwnerNodeInfo));
            }

            writer.writeAttribute("message", StringUtils.join(messages, "\n\n"));
            writer.writeEndElement(); //failure
        }
        writer.writeEndElement(); //testcase

        writer.writeEndElement(); //testsuite
    }

    writer.writeEndElement(); //testsuites
    writer.writeEndDocument();
}

From source file:org.jasig.portal.security.provider.saml.SAMLDelegatedAuthenticationService.java

/**
 * This method processes the SOAP response from the IdP, and converts it
 * for presenting it back to the WSP that requested a delegated SAML
 * assertion./*from  w ww  .j a v  a  2s.  co m*/
 * 
 * @param samlSession SAML session
 * @param authnState 
 * @return true, if successful
 */
private boolean processSOAPResponse(SAMLSession samlSession, DelegatedSAMLAuthenticationState authnState) {
    this.logger.debug("Step 5 of 5: Processing SOAP response");

    try {
        String expression = "/soap:Envelope/soap:Header/ecp:Response";
        InputStream is = new ByteArrayInputStream(authnState.getSoapResponse().getBytes());
        InputSource source = new InputSource(is);
        DOMParser parser = new DOMParser();
        parser.setFeature("http://xml.org/sax/features/namespaces", true);
        parser.parse(source);
        Document doc = parser.getDocument();
        Node node = EXPRESSION_POOL.evaluate(expression, doc, XPathConstants.NODE);

        if (node != null) {
            String responseConsumerURL = node.getAttributes().getNamedItem("AssertionConsumerServiceURL")
                    .getTextContent();

            logger.debug("Found {} node found in SOAP response.", expression);

            if (responseConsumerURL != null
                    && responseConsumerURL.equals(authnState.getResponseConsumerURL())) {
                logger.debug("responseConsumerURL {} matches {}", responseConsumerURL,
                        authnState.getResponseConsumerURL());

                // Retrieve and save the SOAP prefix used
                String soapPrefix = node.getParentNode().getPrefix();
                Element ecpResponse = (Element) node;
                Element soapHeader = (Element) ecpResponse.getParentNode();
                removeAllChildren(soapHeader);

                // Now on to the PAOS Response
                Element paosResponse = doc.createElementNS("urn:liberty:paos:2003-08", "paos:Response");
                paosResponse.setAttribute(soapPrefix + ":mustUnderstand", "1");
                paosResponse.setAttribute(soapPrefix + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

                // messageID is optional
                if (authnState.getPaosMessageID() != null)
                    paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());

                soapHeader.appendChild(paosResponse);

                if (authnState.getRelayStateElement() != null) {
                    Node relayState = doc.importNode(authnState.getRelayStateElement(), true);
                    soapHeader.appendChild(relayState);
                }

                // Store the modified SOAP Request in the SAML Session
                String modifiedSOAPResponse = writeDomToString(doc);
                authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
                return true;
            }

            logger.debug("responseConsumerURL {} does not match {}", responseConsumerURL,
                    authnState.getResponseConsumerURL());
            Document soapFaultMessage = createSOAPFaultDocument(
                    "AssertionConsumerServiceURL attribute missing or not matching the expected value.");
            Element soapHeader = (Element) soapFaultMessage.getFirstChild().getFirstChild();
            // Now on to the PAOS Response
            Element paosResponse = soapFaultMessage.createElementNS("urn:liberty:paos:2003-08",
                    "paos:Response");
            paosResponse.setAttribute(SOAP_PREFIX + ":mustUnderstand", "1");
            paosResponse.setAttribute(SOAP_PREFIX + ":actor", "http://schemas.xmlsoap.org/soap/actor/next");

            // messageID is optional
            if (authnState.getPaosMessageID() != null) {
                paosResponse.setAttribute("refToMessageID", authnState.getPaosMessageID());
            }

            soapHeader.appendChild(paosResponse);

            if (authnState.getRelayStateElement() != null) {
                Node relayState = soapFaultMessage.importNode(authnState.getRelayStateElement(), true);
                soapHeader.appendChild(relayState);
            }
            // Store the SOAP Fault in the SAML Session
            String modifiedSOAPResponse = writeDomToString(soapFaultMessage);
            authnState.setModifiedSOAPResponse(modifiedSOAPResponse);
            sendSOAPFault(samlSession, authnState);
            return false;

        }

        // There was no response for the ECP.  Look for and propagate an error.
        String errorMessage = getSOAPFaultAsString(is);

        logger.warn("No {} node found in SOAP response. Error: {}", expression, errorMessage);

        if (errorMessage != null) {
            throw new DelegatedAuthenticationRuntimeException(errorMessage);
        }

        return false;
    } catch (XPathExpressionException ex) {
        logger.error("XPath programming error.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotRecognizedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException("XPath programming error.", ex);
    } catch (SAXNotSupportedException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (SAXException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (DOMException ex) {
        logger.error("Exception caught when trying to process the SOAP esponse from the IdP.", ex);
        throw new DelegatedAuthenticationRuntimeException(
                "Exception caught when trying to process the SOAP esponse from the IdP.", ex);
    } catch (IOException ex) {
        logger.error(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
        throw new DelegatedAuthenticationRuntimeException(
                "This exception should not ever really occur, as the only I/O this method performs is on a ByteArrayInputStream.",
                ex);
    } catch (SOAPException ex) {
        logger.error("Error processing a SOAP message.", ex);
        throw new DelegatedAuthenticationRuntimeException("Error processing a SOAP message.", ex);
    }
}

From source file:org.structr.web.entity.dom.DOMNode.java

protected void checkIsChild(Node otherNode) throws DOMException {

    if (otherNode instanceof DOMNode) {

        Node _parent = otherNode.getParentNode();

        if (!isSameNode(_parent)) {

            throw new DOMException(DOMException.NOT_FOUND_ERR, NOT_FOUND_ERR_MESSAGE);
        }//from   w w w . j  av  a2 s  . co  m

        // validation successful
        return;
    }

    throw new DOMException(DOMException.NOT_SUPPORTED_ERR, NOT_SUPPORTED_ERR_MESSAGE);
}

From source file:com.gargoylesoftware.htmlunit.html.DomNode.java

/**
 * Check for insertion errors for a new child node. This is overridden by derived
 * classes to enforce which types of children are allowed.
 *
 * @param newChild the new child node that is being inserted below this node
 * @throws DOMException HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does
 * not allow children of the type of the newChild node, or if the node to insert is one of
 * this node's ancestors or this node itself, or if this node is of type Document and the
 * DOM application attempts to insert a second DocumentType or Element node.
 * WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the
 * one that created this node./*  www.j a v  a2  s.  co m*/
 */
protected void checkChildHierarchy(final Node newChild) throws DOMException {
    Node parentNode = this;
    while (parentNode != null) {
        if (parentNode == newChild) {
            throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Child node is already a parent.");
        }
        parentNode = parentNode.getParentNode();
    }
    final Document thisDocument = getOwnerDocument();
    final Document childDocument = newChild.getOwnerDocument();
    if (childDocument != thisDocument && childDocument != null) {
        throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Child node " + newChild.getNodeName()
                + " is not in the same Document as this " + getNodeName() + ".");
    }
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Deletes the specified node.//from  www.  j a v a2s.c o m
 *
 * @param path the path pointing to the node to be deleted.
 */
public boolean deleteNode(Node node, String path) throws XFormsException {
    String canonicalPath = DOMUtil.getCanonicalPath(node);
    if (node == null) {
        LOGGER.warn("Node is null - delete is terminated with no effect.");
        return false;
    }

    //don't delete readonly nodes
    if (isReadonly(node)) {
        LOGGER.warn("Node or one of it's parents is readonly - delete is terminated with no effect.");
        return false;
    }

    //don't delete content of a xmlns Attribute - not clear what Spec means by not allowing to delete a namespace node
    if (node.getNodeName().startsWith("xmlns")) {
        LOGGER.warn("Node is Namespace declaration - delete is terminated with no effect.");
        return false;
    }

    //don't delete root nodes
    if (node.getNodeType() != Node.ATTRIBUTE_NODE && node.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
        LOGGER.warn("Node is a root Node - delete is terminated with no effect.");
        return false;
    }

    //don't delete document nodes
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        LOGGER.warn("Node is a Document Node - delete is terminated with no effect.");
        return false;
    }

    Node canonNode = node;

    if (node.getNodeType() != Node.ATTRIBUTE_NODE) {
        node.getParentNode().removeChild(node);
    } else {
        Attr attr = (Attr) node;
        attr.getOwnerElement().removeAttributeNode(attr);
    }

    // dispatch internal betterform event (for instant repeat updating)
    String[] canonicalParts = XPathUtil.getNodesetAndPredicates(path);
    HashMap map = new HashMap();
    map.put("nodeset", canonicalParts[0]);
    map.put("position", canonicalParts[canonicalParts.length - 1]);
    map.put("canonPath", canonicalPath);
    this.container.dispatch(this.target, BetterFormEventNames.NODE_DELETED, map);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " delete node: instance data after manipulation" + toString(this.instanceDocument));
    }
    return true;
}