Example usage for org.w3c.dom Document importNode

List of usage examples for org.w3c.dom Document importNode

Introduction

In this page you can find the example usage for org.w3c.dom Document importNode.

Prototype

public Node importNode(Node importedNode, boolean deep) throws DOMException;

Source Link

Document

Imports a node from another document to this document, without altering or removing the source node from the original document; this method creates a new copy of the source node.

Usage

From source file:org.apache.ode.bpel.runtime.ASSIGN.java

private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) {
    Document doc = ptr.getOwnerDocument();
    Node parent = ptr.getParentNode();
    if (keepSrcElement) {
        Element replacement = (Element) doc.importNode(src, true);
        parent.replaceChild(replacement, ptr);
        return (lval == ptr) ? replacement : lval;
    }//from w  w  w. j  a  va  2  s  .  c  o  m

    Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getTagName());
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i)
        replacement.appendChild(doc.importNode(nl.item(i), true));
    copyAttributes(doc, ptr, replacement);
    copyAttributes(doc, src, replacement);
    parent.replaceChild(replacement, ptr);
    DOMUtils.copyNSContext(ptr, replacement);

    return (lval == ptr) ? replacement : lval;
}

From source file:org.apache.ode.bpel.runtime.ASSIGN.java

private void copyAttributes(Document doc, Element original, Element replacement) {
    NamedNodeMap attrs = original.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        replacement.setAttributeNodeNS((Attr) doc.importNode(attr, true));
    }/*from  w  ww .j a  v  a2 s  .c o m*/
}

From source file:org.apache.ode.bpel.runtime.AssignHelper.java

private Element replaceElement(Element lval, Element ptr, Element src, boolean keepSrcElement) {
    Document doc = ptr.getOwnerDocument();
    Node parent = ptr.getParentNode();
    if (keepSrcElement) {
        Element replacement = (Element) doc.importNode(src, true);
        parent.replaceChild(replacement, ptr);
        return (lval == ptr) ? replacement : lval;
    }//  ww  w .  j  a v a  2 s. co  m

    Element replacement = doc.createElementNS(ptr.getNamespaceURI(), ptr.getTagName());
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i)
        replacement.appendChild(doc.importNode(nl.item(i), true));
    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (!attr.getName().startsWith("xmlns")) {
            replacement.setAttributeNodeNS((Attr) doc.importNode(attrs.item(i), true));
            // Case of qualified attribute values, we're forced to add corresponding namespace declaration manually
            int colonIdx = attr.getValue().indexOf(":");
            if (colonIdx > 0) {
                String prefix = attr.getValue().substring(0, colonIdx);
                String attrValNs = src.lookupPrefix(prefix);
                if (attrValNs != null)
                    replacement.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs);
            }
        }
    }
    parent.replaceChild(replacement, ptr);
    DOMUtils.copyNSContext(ptr, replacement);

    return (lval == ptr) ? replacement : lval;
}

From source file:org.apache.ode.il.epr.WSAEndpoint.java

public Document toXML() {
    // Wrapping// w  w w . jav  a  2 s . c om
    Document doc = DOMUtils.newDocument();
    Element serviceRef = doc.createElementNS(SERVICE_REF_QNAME.getNamespaceURI(),
            SERVICE_REF_QNAME.getLocalPart());
    doc.appendChild(serviceRef);
    serviceRef.appendChild(doc.importNode(_eprElmt, true));
    return _eprElmt.getOwnerDocument();
}

From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java

public EndpointReference resolveEndpointReference(Element epr) {
    QName elname = new QName(epr.getNamespaceURI(), epr.getLocalName());

    if (__log.isDebugEnabled()) {
        __log.debug("resolveEndpointReference:\n" + prettyPrint(epr));
    }//from   w w  w .  java2  s .co m
    if (!elname.equals(EndpointReference.SERVICE_REF_QNAME))
        throw new IllegalArgumentException(
                "EPR root element " + elname + " should be " + EndpointReference.SERVICE_REF_QNAME);

    Document doc = DOMUtils.newDocument();
    DocumentFragment fragment = doc.createDocumentFragment();
    NodeList children = epr.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i)
        if (children.item(i) instanceof Element)
            fragment.appendChild(doc.importNode(children.item(i), true));
    ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment);
    if (se == null)
        return null;
    return new JbiEndpointReference(se);
}

From source file:org.apache.ode.jbi.EndpointReferenceContextImpl.java

public EndpointReference convertEndpoint(QName eprType, Element epr) {
    Document doc = DOMUtils.newDocument();
    DocumentFragment fragment = doc.createDocumentFragment();
    NodeList children = epr.getChildNodes();
    for (int i = 0; i < children.getLength(); ++i)
        fragment.appendChild(doc.importNode(children.item(i), true));
    ServiceEndpoint se = _ode.getContext().resolveEndpointReference(fragment);
    if (se == null)
        return null;

    return new JbiEndpointReference(se, eprType);

}

From source file:org.apache.ode.store.ProcessStoreImpl.java

/**
 * Create a property mapping based on the initial values in the deployment descriptor.
 *
 * @param dd/* www . j av  a  2  s. co  m*/
 * @return
 */
public static Map<QName, Node> calcInitialProperties(Properties properties, TDeployment.Process dd) {
    HashMap<QName, Node> ret = new HashMap<QName, Node>();

    for (Object key1 : properties.keySet()) {
        String key = (String) key1;
        Document doc = DOMUtils.newDocument();
        doc.appendChild(doc.createElementNS(null, "temporary-simple-type-wrapper"));
        doc.getDocumentElement().appendChild(doc.createTextNode(properties.getProperty(key)));

        ret.put(new QName(key), doc.getDocumentElement());
    }

    for (TDeployment.Process.Property property : dd.getPropertyArray()) {
        Element elmtContent = DOMUtils.getElementContent(property.getDomNode());
        if (elmtContent != null) {
            // We'll need DOM Level 3
            Document doc = DOMUtils.newDocument();
            doc.appendChild(doc.importNode(elmtContent, true));
            ret.put(property.getName(), doc.getDocumentElement());
        } else
            ret.put(property.getName(), property.getDomNode().getFirstChild());

    }
    return ret;
}

From source file:org.apache.ode.utils.DOMUtils.java

public static Document toDOMDocument(Node node) throws TransformerException {
    // If the node is the document, just cast it
    if (node instanceof Document) {
        return (Document) node;
        // If the node is an element
    } else if (node instanceof Element) {
        Element elem = (Element) node;
        // If this is the root element, return its owner document
        if (elem.getOwnerDocument().getDocumentElement() == elem) {
            return elem.getOwnerDocument();
            // else, create a new doc and copy the element inside it
        } else {//  www.ja  v a  2  s  .c om
            Document doc = newDocument();
            doc.appendChild(doc.importNode(node, true));
            return doc;
        }
        // other element types are not handled
    } else {
        throw new TransformerException("Unable to convert DOM node to a Document");
    }
}

From source file:org.apache.openaz.xacml.std.dom.DOMUtil.java

/**
 * Creates a copy of the given <code>Node</code> such that it appears to be the direct child of a
 * <code>Document</code>>
 *
 * @param node the <code>Node</code> to convert
 * @return the new <code>Node</code>
 *//*from   www. j a v a2  s .c o m*/
public static Node getDirectDocumentChild(Node node) throws DOMStructureException {
    Node nodeResult = null;
    try {
        DocumentBuilder documentBuilder = getDocumentBuilder();
        Document documentRoot = documentBuilder.newDocument();
        Node nodeTopRoot = documentRoot.importNode(node, true);
        documentRoot.appendChild(nodeTopRoot);
        nodeResult = documentRoot.getDocumentElement();
    } catch (Exception ex) {
        throw new DOMStructureException("Exception generating Document root Node from Node: " + ex.getMessage(),
                ex);
    }
    return nodeResult;
}

From source file:org.apache.rampart.builder.BindingBuilder.java

protected byte[] doSymmSignature(RampartMessageData rmd, Token policyToken, org.apache.rahas.Token tok,
        Vector sigParts) throws RampartException {

    Document doc = rmd.getDocument();

    RampartPolicyData rpd = rmd.getPolicyData();

    if (policyToken.isDerivedKeys()) {
        try {/*  w w w . j  a  v  a2 s. c  o  m*/
            WSSecDKSign dkSign = new WSSecDKSign();

            // Check whether it is security policy 1.2 and use the secure conversation
            // accordingly
            if (SPConstants.SP_V12 == policyToken.getVersion()) {
                dkSign.setWscVersion(ConversationConstants.VERSION_05_12);
            }

            // Check for whether the token is attached in the message or not
            boolean attached = false;

            if (SPConstants.INCLUDE_TOEKN_ALWAYS == policyToken.getInclusion()
                    || SPConstants.INCLUDE_TOKEN_ONCE == policyToken.getInclusion() || (rmd.isInitiator()
                            && SPConstants.INCLUDE_TOEKN_ALWAYS_TO_RECIPIENT == policyToken.getInclusion())) {
                attached = true;
            }

            // Setting the AttachedReference or the UnattachedReference according to the flag
            OMElement ref;
            if (attached == true) {
                ref = tok.getAttachedReference();
            } else {
                ref = tok.getUnattachedReference();
            }

            if (ref != null) {
                dkSign.setExternalKey(tok.getSecret(), (Element) doc.importNode((Element) ref, true));
            } else if (!rmd.isInitiator() && policyToken.isDerivedKeys()) {

                // If the Encrypted key used to create the derived key is not
                // attached use key identifier as defined in WSS1.1 section
                // 7.7 Encrypted Key reference
                SecurityTokenReference tokenRef = new SecurityTokenReference(doc);
                if (tok instanceof EncryptedKeyToken) {
                    tokenRef.setKeyIdentifierEncKeySHA1(((EncryptedKeyToken) tok).getSHA1());
                    ;
                }
                dkSign.setExternalKey(tok.getSecret(), tokenRef.getElement());

            } else {
                dkSign.setExternalKey(tok.getSecret(), tok.getId());
            }

            // Set the algo info
            dkSign.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
            dkSign.setDerivedKeyLength(rpd.getAlgorithmSuite().getSignatureDerivedKeyLength() / 8);
            if (tok instanceof EncryptedKeyToken) {
                // Set the value type of the reference
                dkSign.setCustomValueType(WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE);
            }

            dkSign.prepare(doc, rmd.getSecHeader());

            if (rpd.isTokenProtection()) {

                // Hack to handle reference id issues
                // TODO Need a better fix
                String sigTokId = tok.getId();
                if (sigTokId.startsWith("#")) {
                    sigTokId = sigTokId.substring(1);
                }
                sigParts.add(new WSEncryptionPart(sigTokId));
            }

            dkSign.setParts(sigParts);

            dkSign.addReferencesToSign(sigParts, rmd.getSecHeader());

            // Do signature
            dkSign.computeSignature();

            // Add elements to header

            if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING)
                    && this.getInsertionLocation() == null) {
                this.setInsertionLocation(RampartUtil

                        .insertSiblingBefore(rmd, this.mainRefListElement, dkSign.getdktElement()));

                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                        dkSign.getSignatureElement()));
            } else {
                this.setInsertionLocation(RampartUtil

                        .insertSiblingAfter(rmd, this.getInsertionLocation(), dkSign.getdktElement()));

                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                        dkSign.getSignatureElement()));
            }

            return dkSign.getSignatureValue();

        } catch (ConversationException e) {
            throw new RampartException("errorInDerivedKeyTokenSignature", e);
        } catch (WSSecurityException e) {
            throw new RampartException("errorInDerivedKeyTokenSignature", e);
        }
    } else {
        try {
            WSSecSignature sig = new WSSecSignature();
            sig.setWsConfig(rmd.getConfig());

            // If a EncryptedKeyToken is used, set the correct value type to
            // be used in the wsse:Reference in ds:KeyInfo
            if (policyToken instanceof X509Token) {
                if (rmd.isInitiator()) {
                    sig.setCustomTokenValueType(
                            WSConstants.SOAPMESSAGE_NS11 + "#" + WSConstants.ENC_KEY_VALUE_TYPE);
                    sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                } else {
                    // the tok has to be an EncryptedKey token
                    sig.setEncrKeySha1value(((EncryptedKeyToken) tok).getSHA1());
                    sig.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
                }

            } else if (policyToken instanceof IssuedToken) {
                if ("urn:oasis:names:tc:SAML:2.0:assertion"
                        .equals(((IssuedToken) policyToken).getRstTokenType())) {
                    sig.setCustomTokenValueType(
                            "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID");
                } else {
                    sig.setCustomTokenValueType(
                            "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID");
                }
                sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
            }

            String sigTokId;

            if (policyToken instanceof SecureConversationToken) {
                sig.setKeyIdentifierType(WSConstants.CUSTOM_SYMM_SIGNING);
                OMElement ref = tok.getAttachedReference();
                if (ref == null) {
                    ref = tok.getUnattachedReference();
                }

                if (ref != null) {
                    sigTokId = SimpleTokenStore.getIdFromSTR(ref);
                } else {
                    sigTokId = tok.getId();
                }
            } else {
                sigTokId = tok.getId();
            }

            // Hack to handle reference id issues
            // TODO Need a better fix
            if (sigTokId.startsWith("#")) {
                sigTokId = sigTokId.substring(1);
            }

            sig.setCustomTokenId(sigTokId);
            sig.setSecretKey(tok.getSecret());

            if (tok.getSecret() == null) {
                sig.setUserInfo(rpd.getRampartConfig().getUser(), rpd.getRampartConfig().getSigCryptoConfig()
                        .getProp().getProperty("org.wso2.carbon.security.crypto.private.key.password"));
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getAsymmetricSignature());
            } else {
                sig.setSignatureAlgorithm(rpd.getAlgorithmSuite().getSymmetricSignature());
            }

            sig.prepare(rmd.getDocument(),
                    RampartUtil.getSignatureCrypto(rpd.getRampartConfig(), rmd.getCustomClassLoader()),
                    rmd.getSecHeader());

            sig.setParts(sigParts);
            sig.addReferencesToSign(sigParts, rmd.getSecHeader());

            // Do signature
            sig.computeSignature();

            if (rpd.getProtectionOrder().equals(SPConstants.ENCRYPT_BEFORE_SIGNING)
                    && this.getInsertionLocation() == null) {
                this.setInsertionLocation(RampartUtil.insertSiblingBefore(rmd, this.mainRefListElement,
                        sig.getSignatureElement()));
            } else {
                this.setInsertionLocation(RampartUtil.insertSiblingAfter(rmd, this.getInsertionLocation(),
                        sig.getSignatureElement()));
            }

            return sig.getSignatureValue();

        } catch (WSSecurityException e) {
            throw new RampartException("errorInSignatureWithACustomToken", e);
        }

    }
}