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.tizzit.util.XercesHelper.java

public static String node2Html(Node node) {
    Document doc = getNewDocument();
    Node newnde = doc.importNode(node, true);
    doc.appendChild(newnde);//www.  jav a  2s  .  c  om

    StringWriter stringOut = new StringWriter();
    try {
        Transformer t = TransformerFactory.newInstance().newTransformer();
        // for "XHTML" serialization, use the output method "xml" and set publicId as shown

        /*t.setOutputProperty(OutputKeys.METHOD, "xml");
         t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD XHTML 1.0 Transitional//EN");
         t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");*/

        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.METHOD, "xml");

        t.transform(new DOMSource(doc), new StreamResult(stringOut));
    } catch (Exception exe) {
        log.error("unknown error occured", exe);
    }
    return stringOut.toString();
}

From source file:org.unitedinternet.cosmo.dav.property.StandardDavProperty.java

/**
 * <p>//from   w  w w.j  a v a 2s  .  c  o m
 * If the property value is an <code>Element</code>, it is imported into
 * the provided <code>Document</code> and returned.
 * </p>
 * <p>
 * If the property value is an <code>XmlSerializable</code>, the element
 * returned by calling {@link XmlSerializable.toXml(Document)} on the
 * value is appended as a child of an element representing the property.
 * </p>
 * <p>
 * If the property value is otherwise not null, {@link Object.toString()} is
 * called upon it, and the result is set as text content of an element
 * representing the property.
 * </p>
 * <p>
 * In all cases, if the property has a language, it is used to set the
 * <code>xml:lang</code> attribute on the property element.
 * </p>
 */
public Element toXml(Document document) {
    Element e = null;

    if (value != null && value instanceof Element) {
        e = (Element) document.importNode((Element) value, true);
    } else {
        e = getName().toXml(document);
        Object v = getValue();
        if (v != null) {
            if (v instanceof XmlSerializable) {
                e.appendChild(((XmlSerializable) v).toXml(document));
            } else {
                DomUtil.setText(e, v.toString());
            }
        }
    }

    if (lang != null) {
        DomUtil.setAttribute(e, XML_LANG, NAMESPACE_XML, lang);
    }

    return e;
}

From source file:org.viafirma.nucleo.firma.imp.FirmaOpenocesAppletBridgeImp.java

/**
 * Postprocesamiento del XML ya firmado por el usuario. En el caso de que el
 * documento original tuviese zonas Signature, se le vuelven a adjuntar, de
 * forma de que el nueo quede el primero.
 * /*from   w w w . j a  v  a 2  s .c o  m*/
 * @param documento
 * @param request
 * @throws TransformerException
 */
private void postprocessXadesEpesEnveloped(Document xmlDocument, Documento documentoOriginal,
        HttpServletRequest request) {
    if (TypeFormatSign.XADES_EPES_ENVELOPED.equals(documentoOriginal.getTypeFormatSign())) {
        Node signatureNode = (Node) request.getSession().getAttribute(Constantes.SIGNATURE_PRINCIPAL);
        request.getSession().removeAttribute(Constantes.SIGNATURE_PRINCIPAL);
        if (signatureNode != null) {
            // Busco el nodo sobre el que adjuntar el resto del contenido
            Element nscontext = XMLUtils.createDSctx(xmlDocument, "ds", Constants.SignatureSpecNS);
            try {
                Node nodo = XPathAPI.selectSingleNode(xmlDocument, "//ds:Signature", nscontext);
                // Aadimos todos los signatures pendientes al documento
                // original.
                Node xmlSignatureNode = xmlDocument.importNode(signatureNode, true);
                nodo.getParentNode().appendChild(xmlSignatureNode);

            } catch (TransformerException e) {
                log.warn("No se puede procesar la Signature previa.", e);
            }
        }
    }
}

From source file:org.wso2.carbon.bpel.core.ode.integration.BPELProcessProxy.java

/**
 * Fill the ODE's message object with the WSDL message parts processed at the message receiver.
 *
 * @param odeRequest      Request message pass in to BPEL engine
 * @param inComingMessage incoming request from message  receiver
 *///from  w ww . j a  va  2  s .co m
private void fillODEMessage(final Message odeRequest, final WSDLAwareMessage inComingMessage) {
    Map<String, OMElement> bodyParts = inComingMessage.getBodyParts();
    Map<String, OMElement> headerParts = inComingMessage.getHeaderParts();
    for (Map.Entry<String, OMElement> bodyPart : bodyParts.entrySet()) {
        if (inComingMessage.isRPC()) {
            /* In RPC Style messages parent element's name is equal to the part name.*/
            odeRequest.setPart(bodyPart.getKey(), OMUtils.toDOM(bodyPart.getValue()));
        } else {
            /* in document style there isn't any relationship between part name and element
            * names. therefore we wrap document style message parts with a element which
            * has part name as it's local name.
            */
            Document doc = DOMUtils.newDocument();
            Element destPart = doc.createElementNS(null, bodyPart.getKey());
            destPart.appendChild(doc.importNode(OMUtils.toDOM(bodyPart.getValue()), true));
            odeRequest.setPart(bodyPart.getKey(), destPart);
        }
    }

    for (Map.Entry<String, OMElement> headerPart : headerParts.entrySet()) {
        odeRequest.setHeaderPart(headerPart.getKey(), OMUtils.toDOM(headerPart.getValue()));
    }
}

From source file:org.wso2.carbon.bpel.core.ode.integration.BPELProcessProxy.java

/**
 * Get the EPR of this service from the WSDL.
 *
 * @param wsdlDef     WSDL Definition//  w w w .  j  ava2 s  .c  om
 * @param serviceName service name
 * @param portName    port name
 * @return XML representation of the EPR
 */
public static Element genEPRfromWSDL(final Definition wsdlDef, final QName serviceName, final String portName) {

    Service serviceDef = wsdlDef.getService(serviceName);
    if (serviceDef != null) {
        Port portDef = serviceDef.getPort(portName);
        if (portDef != null) {
            Document doc = DOMUtils.newDocument();
            Element service = doc.createElementNS(Namespaces.WSDL_11, "service");
            service.setAttribute("name", serviceDef.getQName().getLocalPart());
            service.setAttribute("targetNamespace", serviceDef.getQName().getNamespaceURI());
            Element port = doc.createElementNS(Namespaces.WSDL_11, "port");
            service.appendChild(port);
            port.setAttribute("name", portDef.getName());
            port.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:bindns",
                    portDef.getBinding().getQName().getNamespaceURI());
            port.setAttribute("bindns:binding", portDef.getName());
            for (Object extElmt : portDef.getExtensibilityElements()) {
                if (extElmt instanceof SOAPAddress) {
                    Element soapAddr = doc.createElementNS(Namespaces.SOAP_NS, "address");
                    port.appendChild(soapAddr);
                    soapAddr.setAttribute("location", ((SOAPAddress) extElmt).getLocationURI());
                } else if (extElmt instanceof HTTPAddress) {
                    Element httpAddr = doc.createElementNS(Namespaces.HTTP_NS, "address");
                    port.appendChild(httpAddr);
                    httpAddr.setAttribute("location", ((HTTPAddress) extElmt).getLocationURI());
                } else if (extElmt instanceof SOAP12Address) {
                    Element soap12Addr = doc.createElementNS(Namespaces.SOAP12_NS, "address");
                    port.appendChild(soap12Addr);
                    soap12Addr.setAttribute("location", ((SOAP12Address) extElmt).getLocationURI());
                } else {
                    port.appendChild(
                            doc.importNode(((UnknownExtensibilityElement) extElmt).getElement(), true));
                }
            }
            return service;
        }
    }
    return null;
}

From source file:org.wso2.carbon.bpel.core.ode.integration.BPELProcessProxy.java

/**
 * Create-and-copy a service-ref element.
 *
 * @param elmt Service Reference element
 * @return wrapped element//from ww w  .  j a v  a2 s. co m
 */
public static MutableEndpoint createServiceRef(final Element elmt) {
    Document doc = DOMUtils.newDocument();
    QName elQName = new QName(elmt.getNamespaceURI(), elmt.getLocalName());
    // If we get a service-ref, just copy it, otherwise make a service-ref
    // wrapper
    if (!EndpointReference.SERVICE_REF_QNAME.equals(elQName)) {
        Element serviceref = doc.createElementNS(EndpointReference.SERVICE_REF_QNAME.getNamespaceURI(),
                EndpointReference.SERVICE_REF_QNAME.getLocalPart());
        serviceref.appendChild(doc.importNode(elmt, true));
        doc.appendChild(serviceref);
    } else {
        doc.appendChild(doc.importNode(elmt, true));
    }

    return EndpointFactory.createEndpoint(doc.getDocumentElement());
}

From source file:org.wso2.carbon.bpel.core.ode.integration.store.Utils.java

/**
 * Create a property mapping based on the initial values in the deployment descriptor.
 *
 * @param properties properties//from ww  w.jav  a2s .c  om
 * @param dd         deployment descriptor
 * @return property map
 */
public static Map<QName, Node> calcInitialProperties(final Properties properties,
        final 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());
    }

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

        }
    }
    return ret;
}

From source file:org.wso2.carbon.humantask.core.dao.jpa.openjpa.model.Task.java

public void persistOutput(String outputName, Element outputData) {
    if (StringUtils.isNotEmpty(outputName) && outputData != null) {
        MessageDAO output = new Message();
        output.setMessageType(MessageDAO.MessageType.OUTPUT);

        Document doc = DOMUtils.newDocument();
        Element message = doc.createElement("message");
        doc.appendChild(message);// w  w  w .ja  v a 2 s .c om
        Node importedNode = doc.importNode(outputData, true);
        message.appendChild(importedNode);
        output.setData(message);

        output.setName(QName.valueOf(outputName));
        output.setTask(this);
        this.setOutputMessage(output);
        this.getEntityManager().merge(this);
    }
}

From source file:org.wso2.carbon.humantask.core.engine.runtime.xpath.XPathExpressionRuntime.java

private Element replaceElement(Element lval, Element src) {
    Document doc = lval.getOwnerDocument();
    NodeList nl = src.getChildNodes();
    for (int i = 0; i < nl.getLength(); ++i) {
        lval.appendChild(doc.importNode(nl.item(i), true));
    }//from   ww w .j  a  v a  2s .c  om
    NamedNodeMap attrs = src.getAttributes();
    for (int i = 0; i < attrs.getLength(); ++i) {
        Attr attr = (Attr) attrs.item(i);
        if (!attr.getName().startsWith("xmlns")) {
            lval.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) {
                    lval.setAttributeNS(DOMUtils.NS_URI_XMLNS, "xmlns:" + prefix, attrValNs);
                }
            }
        }
    }

    return lval;
}

From source file:org.wso2.carbon.identity.sts.GenericTokenIssuer.java

/**
 * Create the <code>wst:RequstedSecurityTokenRespoonse</code> element.
 * /* w w w  . j a  va2 s .  c om*/
 * @param data WS-Trust information in the issue request
 * @param notBefore Created time
 * @param notAfter Expiration time
 * @param env Response SOAP envelope
 * @param doc <code>org.w3.dom.Document</code> instance of the response SOAP envelope
 * @param assertion SAML Assertion to be sent in the response.
 * @param encryptedKey Key used to encrypt the SAML assertion.
 * @return <code>wst:RequstedSecurityTokenRespoonse</code> element.
 * @throws TrustException
 * @throws SAMLException
 */
protected OMElement createRSTR(RahasData data, Date notBefore, Date notAfter, SOAPEnvelope env, Document doc,
        Node assertionElem, String assertionId, WSSecEncryptedKey encryptedKey)
        throws TrustException, SAMLException, IdentityProviderException {
    if (log.isDebugEnabled()) {
        log.debug("Begin RSTR Element creation.");
    }

    int wstVersion;
    MessageContext inMsgCtx = null;
    OMElement rstrElem = null;
    OMElement appliesToEpr = null;

    wstVersion = data.getVersion();
    inMsgCtx = data.getInMessageContext();

    rstrElem = TrustUtil.createRequestSecurityTokenResponseElement(wstVersion, env.getBody());
    TrustUtil.createTokenTypeElement(wstVersion, rstrElem).setText(data.getTokenType());

    createDisplayToken(rstrElem, ipData);

    if (encryptedKey != null) {
        OMElement incomingAppliesToEpr = null;
        OMElement appliesToElem = null;
        int keysize = data.getKeysize();
        if (keysize == -1) {
            keysize = encryptedKey.getEphemeralKey().length * 8;
        }

        TrustUtil.createKeySizeElement(wstVersion, rstrElem, keysize);
        incomingAppliesToEpr = data.getAppliesToEpr();
        try {
            Document eprDoc = null;
            eprDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(new ByteArrayInputStream(incomingAppliesToEpr.toString().getBytes()));
            appliesToEpr = (OMElement) doc.importNode(eprDoc.getDocumentElement(), true);
        } catch (Exception e) {
            throw new TrustException(TrustException.REQUEST_FAILED, e);
        }

        appliesToElem = rstrElem.getOMFactory()
                .createOMElement(new QName(RahasConstants.WSP_NS,
                        RahasConstants.IssuanceBindingLocalNames.APPLIES_TO, RahasConstants.WSP_PREFIX),
                        rstrElem);
        appliesToElem.addChild(appliesToEpr);
    }

    DateFormat zulu = null;
    OMElement reqSecTokenElem = null;
    Node assertionElement = null;
    Token assertionToken = null;

    // Use GMT time in milliseconds
    zulu = new XmlSchemaDateFormat();

    // Add the Lifetime element
    TrustUtil.createLifetimeElement(wstVersion, rstrElem, zulu.format(notBefore), zulu.format(notAfter));

    reqSecTokenElem = TrustUtil.createRequestedSecurityTokenElement(wstVersion, rstrElem);
    assertionElement = doc.importNode(assertionElem, true);
    reqSecTokenElem.addChild((OMNode) assertionElement);

    if (log.isDebugEnabled()) {
        log.debug(assertionElement.toString());
    }

    if (encryptedKey != null) {
        encryptSAMLAssertion(doc, (Element) assertionElement, encryptedKey);
    }

    createAttachedRef(rstrElem, assertionId);
    createUnattachedRef(rstrElem, assertionId);

    // Store the Token
    assertionToken = new Token(assertionId, (OMElement) doc.importNode(assertionElem, true), notBefore,
            notAfter);

    // At this point we definitely have the secret
    // Otherwise it should fail with an exception earlier
    assertionToken.setSecret(data.getEphmeralKey());
    TrustUtil.getTokenStore(inMsgCtx).add(assertionToken);

    // Creating the ReqProoftoken - END
    if (log.isDebugEnabled()) {
        log.debug("RSTR Elem created.");
    }

    return rstrElem;
}