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.hise.engine.jaxws.HISEJaxWSClient.java

@Transactional
public Node invoke(Node message, Node epr) {
    try {/*ww w . j a v  a  2  s .  c om*/

        Dispatch<SOAPMessage> dispatch = destinationService.createDispatch(destinationPort, SOAPMessage.class,
                Service.Mode.MESSAGE);

        String address = getAddressFromEpr(epr);
        if (!address.equals("")) {
            __log.debug("sending to address " + address);
            dispatch.getRequestContext().put(Dispatch.ENDPOINT_ADDRESS_PROPERTY, address);
        }

        SOAPMessage m;
        m = messageFactory.createMessage();
        Document doc = m.getSOAPBody().getOwnerDocument();
        m.getSOAPBody().appendChild(doc.importNode(message, true));
        return dispatch.invoke(m).getSOAPBody();
    } catch (SOAPException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hise.engine.jaxws.HISEJaxWSService.java

@Transactional
public SOAPMessage invoke(final SOAPMessage request) {
    try {//from www .  j av a 2s.  c o m
        // TransactionStatus tx = transactionManager.getTransaction(new DefaultTransactionDefinition());
        //                    assert transactionManager.isValidateExistingTransaction();
        MessageContext c = context.getMessageContext();
        Object operationInfo = c.get("org.apache.cxf.service.model.OperationInfo");
        QName operation = (QName) operationInfo.getClass().getMethod("getName").invoke(operationInfo);
        QName portType = (QName) c.get("javax.xml.ws.wsdl.interface");
        QName operation2 = (QName) c.get("javax.xml.ws.wsdl.operation");

        Element body = request.getSOAPBody();
        __log.debug("invoking " + request + " operation:" + operation + " portType:" + portType + " operation2:"
                + operation2);
        Node approveResponseHeader = hiseEngine.receive(HISEJaxWSService.this, portType,
                operation.getLocalPart(), body, request.getSOAPHeader());
        SOAPMessage m = messageFactory.createMessage();

        Document doc = m.getSOAPHeader().getOwnerDocument();
        if (approveResponseHeader != null) {
            m.getSOAPHeader().appendChild(doc.importNode(approveResponseHeader, true));
        }
        return m;
    } catch (Exception e) {
        throw new RuntimeException("Error during receiving message ", e);
    }
}

From source file:org.apache.jackrabbit.core.config.RepositoryConfigurationParser.java

/**
 * Parses data store configuration. Data store configuration uses the following format:
 * <pre>//from   w w  w .j av  a2  s  .c o  m
 *   &lt;DataStore class="..."&gt;
 *     &lt;param name="..." value="..."&gt;
 *     ...
 *   &lt;/DataStore&gt;
 * </pre>
 * Its also possible to configure a multi data store. The configuration uses following format:
 * <pre>
 *   &lt;DataStore class="org.apache.jackrabbit.core.data.MultiDataStore"&gt;
 *     &lt;param name="primary" value="org.apache.jackrabbit.core.data.db.XXDataStore"&gt;
 *         &lt;param name="..." value="..."&gt;
 *         ...
 *     &lt;/param&gt;
 *     &lt;param name="archive" value="org.apache.jackrabbit.core.data.db.XXDataStore"&gt;
 *         &lt;param name="..." value="..."&gt;
 *         ...
 *     &lt;/param&gt;
 *   &lt;/DataStore&gt;
 * </pre>
 * <p/>
 * <code>DataStore</code> is a {@link #parseBeanConfig(Element,String) bean configuration}
 * element.
 *
 * @param parent configuration element
 * @param directory the repository directory
 * @return data store factory
 * @throws ConfigurationException if the configuration is broken
 */
protected DataStoreFactory getDataStoreFactory(final Element parent, final String directory)
        throws ConfigurationException {
    return new DataStoreFactory() {
        public DataStore getDataStore() throws RepositoryException {
            NodeList children = parent.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE
                        && DATA_STORE_ELEMENT.equals(child.getNodeName())) {
                    BeanConfig bc = parseBeanConfig(parent, DATA_STORE_ELEMENT);
                    bc.setValidate(false);
                    DataStore store = bc.newInstance(DataStore.class);
                    if (store instanceof MultiDataStore) {
                        DataStore primary = null;
                        DataStore archive = null;
                        NodeList subParamNodes = child.getChildNodes();
                        for (int x = 0; x < subParamNodes.getLength(); x++) {
                            Node paramNode = subParamNodes.item(x);
                            if (paramNode.getNodeType() == Node.ELEMENT_NODE && (PRIMARY_DATASTORE_ATTRIBUTE
                                    .equals(paramNode.getAttributes().getNamedItem("name").getNodeValue())
                                    || ARCHIVE_DATASTORE_ATTRIBUTE.equals(
                                            paramNode.getAttributes().getNamedItem("name").getNodeValue()))) {
                                try {
                                    Document document = DocumentBuilderFactory.newInstance()
                                            .newDocumentBuilder().newDocument();
                                    Element newParent = document.createElement("parent");
                                    document.appendChild(newParent);
                                    Element datastoreElement = document.createElement(DATA_STORE_ELEMENT);
                                    newParent.appendChild(datastoreElement);
                                    NodeList childNodes = paramNode.getChildNodes();
                                    for (int y = 0; childNodes.getLength() > y; y++) {
                                        datastoreElement
                                                .appendChild(document.importNode(childNodes.item(y), true));
                                    }
                                    NamedNodeMap attributes = paramNode.getAttributes();
                                    for (int z = 0; attributes.getLength() > z; z++) {
                                        Node item = attributes.item(z);
                                        datastoreElement.setAttribute(CLASS_ATTRIBUTE, item.getNodeValue());
                                    }
                                    DataStore subDataStore = getDataStoreFactory(newParent, directory)
                                            .getDataStore();
                                    if (!MultiDataStoreAware.class.isAssignableFrom(subDataStore.getClass())) {
                                        throw new ConfigurationException(
                                                "Only MultiDataStoreAware datastore's can be used within a MultiDataStore.");
                                    }
                                    String type = getAttribute((Element) paramNode, NAME_ATTRIBUTE);
                                    if (PRIMARY_DATASTORE_ATTRIBUTE.equals(type)) {
                                        primary = subDataStore;
                                    } else if (ARCHIVE_DATASTORE_ATTRIBUTE.equals(type)) {
                                        archive = subDataStore;
                                    }
                                } catch (Exception e) {
                                    throw new ConfigurationException(
                                            "Failed to parse the MultiDataStore element.", e);
                                }
                            }
                        }
                        if (primary == null || archive == null) {
                            throw new ConfigurationException(
                                    "A MultiDataStore must have configured a primary and archive datastore");
                        }
                        ((MultiDataStore) store).setPrimaryDataStore(primary);
                        ((MultiDataStore) store).setArchiveDataStore(archive);
                    }
                    store.init(directory);
                    return store;
                }
            }
            return null;
        }
    };
}

From source file:org.apache.jackrabbit.webdav.client.methods.PollMethod.java

/**
 *
 * @param root/*from   ww w.j  a  v  a 2s  .c o  m*/
 * @return
 */
private boolean buildDiscoveryFromRoot(Element root) {
    if (DomUtil.matches(root, XML_EVENTDISCOVERY, ObservationConstants.NAMESPACE)) {
        eventDiscovery = new EventDiscovery();
        ElementIterator it = DomUtil.getChildren(root, XML_EVENTBUNDLE, ObservationConstants.NAMESPACE);
        while (it.hasNext()) {
            final Element ebElement = it.nextElement();
            EventBundle eb = new EventBundle() {
                public Element toXml(Document document) {
                    return (Element) document.importNode(ebElement, true);
                }
            };
            eventDiscovery.addEventBundle(eb);
        }
        return true;
    } else {
        log.debug("Missing 'eventdiscovery' response body in POLL method.");
    }
    return false;
}

From source file:org.apache.ode.axis2.httpbinding.HttpHelper.java

/**
 * Build a "details" element that looks like this:
 *
 * @param method/*from   w w  w  .  j a  v  a 2s .c  o m*/
 * @return
 * @throws IOException
 */
public static Element prepareDetailsElement(HttpMethod method) {
    Header h = method.getResponseHeader("Content-Type");
    String receivedType = h != null ? h.getValue() : null;
    boolean bodyIsXml = receivedType != null && HttpUtils.isXml(receivedType);

    Document doc = DOMUtils.newDocument();
    Element detailsEl = doc.createElementNS(null, "details");
    Element statusLineEl = statusLineToElement(doc, method.getStatusLine());
    detailsEl.appendChild(statusLineEl);

    // set the body if any
    try {
        final String body = method.getResponseBodyAsString();
        if (StringUtils.isNotEmpty(body)) {
            Element bodyEl = doc.createElementNS(null, "responseBody");
            detailsEl.appendChild(bodyEl);
            // first, try to parse the body as xml
            // if it fails, put it as string in the body element
            boolean exceptionDuringParsing = false;
            if (bodyIsXml) {
                try {
                    Element parsedBodyEl = DOMUtils.stringToDOM(body);
                    bodyEl.appendChild(doc.importNode(parsedBodyEl, true));
                } catch (Exception e) {
                    String errmsg = "Unable to parse the response body as xml. Body will be inserted as string.";
                    if (log.isDebugEnabled())
                        log.debug(errmsg, e);
                    exceptionDuringParsing = true;
                }
            }
            if (!bodyIsXml || exceptionDuringParsing) {
                bodyEl.setTextContent(body);
            }
        }
    } catch (IOException e) {
        if (log.isWarnEnabled())
            log.warn("Exception while loading response body", e);
    }
    return detailsEl;
}

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * Create the element to be associated with this part into the {@link org.apache.ode.bpel.iapi.Message}.
 * <p/>If the part has a non-null element name, the bodyElement is simply appended.
 * Else if the bodyElement has a text content, the value is set to the message.
 * Else append all nodes of bodyElement to the returned element. Attributes are ignored.
 * <p/>/*from   ww w. j av  a 2s. com*/
 * The name of the returned element is the part name.
 *
 * @param part
 * @param receivedElement
 * @return the element to insert "as is" to ODE message
 */
public Element createPartElement(Part part, Element receivedElement) {
    Document doc = DOMUtils.newDocument();
    Element partElement = doc.createElementNS(null, part.getName());
    if (part.getElementName() != null) {
        partElement.appendChild(doc.importNode(receivedElement, true));
    } else {
        if (DOMUtils.isEmptyElement(receivedElement)) {
            // Append an empty text node.
            // Warning! setting an empty string with setTextContent has not effect. See javadoc.
            partElement.appendChild(doc.createTextNode(""));
        } else {
            // No need to make the distinction between simple and complex types, importNode will handle it
            // !!! Attributes are ignored
            for (int m = 0; m < receivedElement.getChildNodes().getLength(); m++) {
                Node child = receivedElement.getChildNodes().item(m);
                partElement.appendChild(doc.importNode(child, true));
            }
        }
    }
    return partElement;
}

From source file:org.apache.ode.axis2.ODEService.java

/**
 * Get the EPR of this service from the WSDL.
 *
 * @param name     service name/*  www. jav a  2s .  c  om*/
 * @param portName port name
 * @return XML representation of the EPR
 */
public static Element genEPRfromWSDL(Definition wsdlDef, QName name, String portName) {
    Service serviceDef = wsdlDef.getService(name);
    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 {
                    port.appendChild(
                            doc.importNode(((UnknownExtensibilityElement) extElmt).getElement(), true));
                }
            }
            return service;
        }
    }
    return null;
}

From source file:org.apache.ode.axis2.ODEService.java

/**
 * Create-and-copy a service-ref element.
 *
 * @param elmt/*from w w w  . j  ava 2 s. com*/
 * @return wrapped element
 */
public static MutableEndpoint createServiceRef(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.apache.ode.axis2.soapbinding.SoapMessageConverter.java

@SuppressWarnings("unchecked")
public void extractSoapBodyParts(org.apache.ode.bpel.iapi.Message message,
        org.apache.axiom.soap.SOAPBody soapBody, SOAPBody bodyDef, Message msg, String rpcWrapper)
        throws AxisFault {

    List<Part> bodyParts = msg.getOrderedParts(bodyDef.getParts());

    if (_isRPC) {
        QName rpcWrapQName = new QName(bodyDef.getNamespaceURI(), rpcWrapper);
        OMElement partWrapper = soapBody.getFirstChildWithName(rpcWrapQName);
        if (partWrapper == null)
            throw new OdeFault(
                    __msgs.msgSoapBodyDoesNotContainExpectedPartWrapper(_serviceName, _portName, rpcWrapQName));
        // In RPC the body element is the operation name, wrapping parts. Order doesn't really matter as far as
        // we're concerned. All we need to do is copy the soap:body children, since doc-lit rpc looks the same
        // in ode and soap.
        for (Part pdef : bodyParts) {
            OMElement srcPart = partWrapper.getFirstChildWithName(new QName(null, pdef.getName()));
            if (srcPart == null)
                throw new OdeFault(__msgs.msgSOAPBodyDoesNotContainRequiredPart(pdef.getName()));
            message.setPart(srcPart.getLocalName(), OMUtils.toDOM(srcPart));
        }//from ww  w. j  ava  2s. c  om

    } else {
        // In doc-literal style, we expect the elements in the body to correspond (in order) to the
        // parts defined in the binding. All the parts should be element-typed, otherwise it is a mess.
        Iterator<OMElement> srcParts = soapBody.getChildElements();
        for (Part partDef : bodyParts) {
            if (!srcParts.hasNext())
                throw new OdeFault(__msgs.msgSOAPBodyDoesNotContainRequiredPart(partDef.getName()));

            OMElement srcPart = srcParts.next();
            if (partDef.getElementName() == null)
                throw new OdeFault(__msgs.msgBindingDefinesNonElementDocListParts());
            if (!srcPart.getQName().equals(partDef.getElementName()))
                throw new OdeFault(
                        __msgs.msgUnexpectedElementInSOAPBody(srcPart.getQName(), partDef.getElementName()));
            Document doc = DOMUtils.newDocument();
            Element destPart = doc.createElementNS(null, partDef.getName());
            destPart.appendChild(doc.importNode(OMUtils.toDOM(srcPart), true));
            message.setPart(partDef.getName(), destPart);
        }
    }
}

From source file:org.apache.ode.bpel.compiler.AssignGenerator.java

private OAssign.RValue compileLiteral(LiteralVal from) {
    Element literal = from.getLiteral();
    Document newDoc = DOMUtils.newDocument();
    Element clone = (Element) newDoc.importNode(literal, true);
    newDoc.appendChild(clone);/*www .  j a  v  a2 s .  co  m*/
    return new OAssign.Literal(_context.getOProcess(), newDoc);
}