Example usage for org.w3c.dom Element getOwnerDocument

List of usage examples for org.w3c.dom Element getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.chiba.xml.xforms.constraints.RelevanceSelector.java

private static void addChildren(Element relevantElement, NodeImpl instanceNode) {
    Document ownerDocument = relevantElement.getOwnerDocument();
    NodeList instanceChildren = instanceNode.getChildNodes();

    for (int index = 0; index < instanceChildren.getLength(); index++) {
        NodeImpl instanceChild = (NodeImpl) instanceChildren.item(index);

        if (isEnabled(instanceChild)) {
            switch (instanceChild.getNodeType()) {
            case Node.TEXT_NODE:
                /* rather not, otherwise we cannot follow specs when
                 * serializing to multipart/form-data for example
                 *//from w  ww .jav  a 2  s  .c  o  m
                // denormalize text for better whitespace handling during serialization
                List list = DOMWhitespace.denormalizeText(instanceChild.getNodeValue());
                for (int item = 0; item < list.size(); item++) {
                    relevantElement.appendChild(ownerDocument.createTextNode(list.get(item).toString()));
                }
                */
                relevantElement.appendChild(ownerDocument.createTextNode(instanceChild.getNodeValue()));
                break;
            case Node.CDATA_SECTION_NODE:
                relevantElement.appendChild(ownerDocument.createCDATASection(instanceChild.getNodeValue()));
                break;
            case Node.ELEMENT_NODE:
                addElement(relevantElement, instanceChild);
                break;
            default:
                // ignore
                break;
            }
        }
    }
}

From source file:org.chiba.xml.xforms.ui.state.UIElementStateUtil.java

/**
 * Creates the state element./* www .  j a  va  2 s  . c o m*/
 *
 * @param parent the parent element to use.
 * @return the state element.
 */
public static Element createStateElement(Element parent) {
    Element state = DOMUtil.findFirstChildNS(parent, NamespaceConstants.CHIBA_NS, UIElementState.STATE_ELEMENT);
    if (state != null) {
        return state;
    }

    Document document = parent.getOwnerDocument();
    state = document.createElementNS(NamespaceConstants.CHIBA_NS,
            NamespaceConstants.CHIBA_PREFIX + ":" + UIElementState.STATE_ELEMENT);
    parent.appendChild(state);

    return state;
}

From source file:org.chiba.xml.xforms.xpath.InstanceFactory.java

/**
 * Creates the specified child element./*from w ww .  j  ava  2 s.  c  om*/
 * <p/>
 * The child element will not be created if one of the following holds:
 * <ol>
 * <li>the index is greater than the parent's children elements number</li>
 * <li>the namespace prefix is unknown</li>
 * </ol>
 *
 * @param parent the parent element.
 * @param name   the name of the child element.
 * @param index  the index of the child element.
 * @return <code>true</code> if the child element has been created successfully,
 *         otherwise <code>false</code>.
 */
private boolean createChildElement(Element parent, String name, int index) {
    if (index > parent.getChildNodes().getLength()) {
        LOGGER.error("child position too big: " + (index + 1));
        return false;
    }

    // check for child element namespace
    int nsSeparator = name.indexOf(':');
    String nsUri = null;

    if (nsSeparator > -1) {
        // resolve namespace uri
        String nsPrefix = name.substring(0, nsSeparator);
        nsUri = NamespaceCtx.getNamespaceURI(parent, nsPrefix);

        if (nsUri == null) {
            LOGGER.error("namespace prefix unknown: " + nsPrefix);
            return false;
        }
    }

    // create child element
    Element child = parent.getOwnerDocument().createElementNS(nsUri, name);
    parent.appendChild(child);

    return true;
}

From source file:org.chiba.xml.xpath.impl.JXPathDOMFactory.java

/**
 * Creates the specified child element.//from   w  w  w  .j av a  2s  . co  m
 * <p/>
 * The child element will not be created if one of the following holds:
 * <ol>
 * <li>the index is greater than the parent's children elements number</li>
 * <li>the namespace prefix is unknown</li>
 * </ol>
 *
 * @param parent the parent element.
 * @param name   the name of the child element.
 * @param index  the index of the child element.
 * @return <code>true</code> if the child element has been created successfully,
 *         otherwise <code>false</code>.
 */
private boolean createChildElement(Element parent, String name, int index) {
    if (index > parent.getChildNodes().getLength()) {
        LOGGER.error("child position too big: " + (index + 1));
        return false;
    }

    // check for child element namespace
    int nsSeparator = name.indexOf(':');
    String nsUri = null;

    if (nsSeparator > -1) {
        // resolve namespace uri
        String nsPrefix = name.substring(0, nsSeparator);
        nsUri = NamespaceResolver.getNamespaceURI(parent, nsPrefix);

        if (nsUri == null) {
            LOGGER.error("namespace prefix unknown: " + nsPrefix);
            return false;
        }
    }

    // create child element
    Element child = parent.getOwnerDocument().createElementNS(nsUri, name);
    parent.appendChild(child);

    return true;
}

From source file:org.codice.ddf.security.claims.attributequery.common.AttributeQueryClient.java

/**
 * Signs AttributeQuery request./*from   w  w  w .  ja v a  2s  .c  om*/
 *
 * @param attributeQuery request to be signed.
 * @return Document of the AttributeQuery.
 */
private Document signRequest(AttributeQuery attributeQuery) throws AttributeQueryException {
    Element soapElement;
    try {
        // Create and set signature for request.
        simpleSign.signSamlObject(attributeQuery);

        // Create soap message for request.
        soapElement = createSoapMessage(attributeQuery);

        // Sign soap message.
        Signer.signObject(attributeQuery.getSignature());
    } catch (SignatureException | SimpleSign.SignatureException e) {
        throw new AttributeQueryException("Error occurred during signing of the request.", e);
    }

    // Print AttributeQuery Request.
    if (LOGGER.isTraceEnabled()) {
        printXML("SAML Protocol AttributeQuery Request:\n{}", soapElement);
    }
    return soapElement.getOwnerDocument();
}

From source file:org.commonjava.maven.galley.maven.model.view.AbstractMavenElementView.java

/**
 * Append new children elements to the final result(collapsed) when there are children ones found in
 * overlapping parents elements, but not found in current element children.
 *
 * @param current The element which will be collapsed during this process.
 * @param step Iteration counter./*from  w w w .ja  v  a2  s  . c  om*/
 * @return Final collapsed element.
 */
@SuppressWarnings("UnusedReturnValue")
private Element addToCollapsedChildElements(Element current, int step) {
    List<Element> parents = elementsAwaitingCollapse;
    while (!isElementStackEmpty(parents) && step < parents.size()) {
        NodeList originalElementChildNodeList = current.getChildNodes();
        List<String> originalElementChildNameList = new ArrayList<>();
        for (int i = 0; i <= originalElementChildNodeList.getLength(); i++) {
            Node node = originalElementChildNodeList.item(i);
            if (!(node instanceof Element)) {
                continue;
            }
            originalElementChildNameList.add(node.getNodeName());
        }

        NodeList nodeList = parents.get(step).getChildNodes();
        for (int i = 0; i <= nodeList.getLength(); i++) {
            Node node = nodeList.item(i);
            if (!(node instanceof Element)) {
                continue;
            }

            if (!originalElementChildNameList.contains(node.getNodeName())) {
                Document dom = current.getOwnerDocument();
                Element child = dom.createElement(node.getNodeName());
                child.setTextContent(node.getTextContent());
                current.appendChild(child);
            }
        }
        step++;
        addToCollapsedChildElements(current, step);
    }
    return current;
}

From source file:org.commonjava.maven.galley.maven.parse.XMLInfrastructure.java

public Element createElement(final Node in, final String relativePath, final Map<String, String> leafElements) {
    final Document doc;
    final Element below;
    if (in instanceof Document) {
        doc = (Document) in;//from  ww w . j  a v a 2 s  .  c om
        below = doc.getDocumentElement();
    } else if (in instanceof Element) {
        below = (Element) in;
        doc = below.getOwnerDocument();
    } else {
        throw new IllegalArgumentException("Cannot create nodes/content under a node of type: " + in);
    }

    Element insertionPoint = below;
    if (relativePath != null && relativePath.length() > 0 && !"/".equals(relativePath)) {
        final String[] intermediates = relativePath.split("/");

        // DO NOT traverse last "intermediate"...this will be the new element!
        for (int i = 0; i < intermediates.length - 1; i++) {
            final NodeList nl = insertionPoint.getElementsByTagNameNS(below.getNamespaceURI(),
                    intermediates[i]);
            if (nl != null && nl.getLength() > 0) {
                insertionPoint = (Element) nl.item(0);
            } else {
                final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[i]);
                insertionPoint.appendChild(e);
                insertionPoint = e;
            }
        }

        final Element e = doc.createElementNS(below.getNamespaceURI(), intermediates[intermediates.length - 1]);
        insertionPoint.appendChild(e);
        insertionPoint = e;
    }

    for (final Entry<String, String> entry : leafElements.entrySet()) {
        final String key = entry.getKey();
        final String value = entry.getValue();

        final Element e = doc.createElementNS(below.getNamespaceURI(), key);
        insertionPoint.appendChild(e);
        e.setTextContent(value);
    }

    return insertionPoint;
}

From source file:org.craftercms.cstudio.share.forms.impl.FormServiceBaseImpl.java

/**
 * merge the instance data with the document
 * /* ww w.  ja  v a 2 s.co  m*/
 * @param xformDocument
 * @param model
 * @return
 */
protected Document mergeInstanceDataWithForm(Document xformDocument, Map<String, Document> model,
        final String namespace) {

    Document retDocument = xformDocument;

    if (model != null) {

        XPathFactory factory = XPathFactory.newInstance();
        XPath xPath = factory.newXPath();

        try {

            NamespaceContext cstudio = new NamespaceContext() {

                public String getNamespaceURI(String prefix) {

                    String uri = "";
                    if (prefix.equals(namespace))
                        uri = "http://www.w3.org/2002/xforms";

                    return uri;
                }

                @SuppressWarnings("unchecked")
                public Iterator getPrefixes(String val) {

                    return null;
                }

                public String getPrefix(String uri) {

                    return null;
                }

            };

            xPath.setNamespaceContext(cstudio);
            XPathExpression xPathExpression = xPath.compile("//" + namespace + ":instance");

            // DOMSource source = new DOMSource(xformDocument);
            // StringWriter xmlAsWriter = new StringWriter();
            // StreamResult result = new StreamResult(xmlAsWriter);
            // TransformerFactory.newInstance().newTransformer().transform(source,
            // result);
            StringReader xmlReader = new StringReader(DomUtils.xmlToString(xformDocument));
            InputSource documentAsInputSource = new InputSource(xmlReader);

            // using implementation here, see article
            // http://onjava.com/pub/a/onjava/2005/01/12/xpath.html
            DTMNodeList nodes = (DTMNodeList) xPathExpression.evaluate(documentAsInputSource,
                    XPathConstants.NODESET);

            int nodeCount = nodes.getLength();

            for (int i = 0; i < nodeCount; i++) {
                Element currentNode = (Element) nodes.item(i);
                String modelId = currentNode.getAttribute("id");

                Document documentToInsert = model.get(modelId);

                if (documentToInsert != null) {

                    Element importedModelRoot = documentToInsert.getDocumentElement();

                    retDocument = currentNode.getOwnerDocument();
                    Node importedModel = retDocument.importNode(importedModelRoot, true);

                    currentNode.appendChild(importedModel);
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    return retDocument;
}

From source file:org.dhatim.delivery.dom.DOMBuilder.java

/**
 * Set the DOM Element node on which the parsed content it to be added.
 * <p/>/*from  w ww  . j a  v  a  2  s  .c o  m*/
 * Used to merge ownerDocument fragments etc.
 * @param appendElement The append DOM element.
 */
public void setAppendElement(Element appendElement) {
    ownerDocument = appendElement.getOwnerDocument();
    // Initialise the stack with the append element node.
    nodeStack.push(appendElement);
}

From source file:org.dhatim.delivery.dom.serialize.TextSerializationUnit.java

public static Element createTextElement(Element element, String templatingResult) {
    Document ownerDocument = element.getOwnerDocument();
    Element resultElement = ownerDocument.createElementNS(Namespace.SMOOKS_URI, "text");
    resultElement.appendChild(ownerDocument.createTextNode(templatingResult));
    return resultElement;
}