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.kuali.rice.kew.xml.DocumentTypeXmlParser.java

/**
 * Parses any custom XML configuration if present and returns it as an XML string.
 * If no custom XML elements are present in the policy configuration, null is returned.
 * @param policyNode the document type policy Node
 * @return XML configuration string or null
 * @throws ParserConfigurationException//from w  ww .j  a v  a 2s  . com
 */
private static String parseDocumentPolicyCustomXMLConfig(Node policyNode) throws ParserConfigurationException {
    final Collection<String> KNOWN_POLICY_ELEMENTS = Arrays
            .asList(new String[] { "name", "value", "stringValue" });
    // Store any other elements as XML in the policy string value
    Document policyConfig = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = policyConfig.createElement("config");
    policyConfig.appendChild(root);
    // add unknown nodes from the config document
    NodeList children = policyNode.getChildNodes();
    for (int j = 0; j < children.getLength(); j++) {
        Node c = children.item(j);
        if (c instanceof Element && !KNOWN_POLICY_ELEMENTS.contains(c.getNodeName())) {
            root.appendChild(policyConfig.importNode(c, true));
        }
    }
    // if there are in-fact custom xml configuration nodes, then go ahead and save the config doc as XML
    return (root.getChildNodes().getLength() > 0) ? XmlJotter.jotDocument(policyConfig) : null;
}

From source file:org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate.java

protected BeanDefinition handleSpringElements(Element element, BeanDefinition parent) {

    // these are only called if they are at a "top level" - if they are nested inside
    // other spring elements then spring will handle them itself

    if (SpringXMLUtils.isLocalName(element, BEANS)) {
        // the delegate doesn't support the full spring schema, but it seems that
        // we can invoke the DefaultBeanDefinitionDocumentReader via registerBeanDefinitions
        // but we need to create a new DOM document from the element first
        try {//from  w  w  w. j  ava  2s . c  om
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            doc.appendChild(doc.importNode(element, true));
            spring.registerBeanDefinitions(doc, getReaderContext());
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        }
        return parent;
    }

    else if (SpringXMLUtils.isLocalName(element, PROPERTY_ELEMENT)) {
        parsePropertyElement(element, parent);
        return parent;
    }

    // i am trying to keep these to a minimum - using anything but "bean" is a recipe
    // for disaster - we already have problems with "property", for example.

    //        else if (isLocalName(element, MAP_ELEMENT))
    //        {
    //            // currently unused?
    //            parseMapElement(element, bd);
    //        }
    //        else if (isLocalName(element, LIST_ELEMENT))
    //        {
    //            // currently unused?
    //            parseListElement(element, bd);
    //        }
    //        else if (isLocalName(element, SET_ELEMENT))
    //        {
    //            // currently unused?
    //            parseSetElement(element, bd);
    //        }

    else if (SpringXMLUtils.isLocalName(element, BEAN_ELEMENT)) {
        BeanDefinitionHolder holder = parseBeanDefinitionElement(element, parent);
        registerBeanDefinitionHolder(holder);
        return holder.getBeanDefinition();
    } else {
        throw new IllegalStateException(
                "Unexpected Spring element: " + SpringXMLUtils.elementToString(element));
    }
}

From source file:org.mule.transport.legstar.transformer.AbstractHostToXmlMuleTransformer.java

/**
 * Merges an XML fragment as a child of a holder element.
 * //from   w  w w  .j av  a 2 s. c  o  m
 * @param docBuilder the document builder for DOM documents
 * @param partXml the XML representation of the part to merge
 * @param partID a part identifier
 * @param docResult the result DOM document
 * @param elHolder the holder DOM element
 * @throws TransformerException if merge operation fails
 */
public void mergeXml(final DocumentBuilder docBuilder, final String partXml, final String partID,
        final Document docResult, final Element elHolder) throws TransformerException {
    try {
        Document docInput = docBuilder.parse(new InputSource(new StringReader(partXml)));
        NodeList nodeList = docInput.getElementsByTagName(partID);
        if (nodeList.getLength() > 0) {
            Node nodeInDocInput = nodeList.item(0);
            /* Import foreign node */
            Node nodeInDocResult = docResult.importNode(nodeInDocInput, true);
            elHolder.appendChild(nodeInDocResult);
        }
    } catch (DOMException e) {
        throw new TransformerException(getI18NMessages().hostTransformFailure(), this, e);
    } catch (SAXException e) {
        throw new TransformerException(getI18NMessages().hostTransformFailure(), this, e);
    } catch (IOException e) {
        throw new TransformerException(getI18NMessages().hostTransformFailure(), this, e);
    }
}

From source file:org.mycore.common.xml.MCRXMLFunctions.java

/**
 * The method return a org.w3c.dom.NodeList as subpath of the doc input
 * NodeList selected by a path as String.
 *
 * @param doc//  ww w  .  j  a v  a  2s  . com
 *            the input org.w3c.dom.Nodelist
 * @param path
 *            the path of doc as String
 * @return a subpath of doc selected by path as org.w3c.dom.NodeList
 */
public static NodeList getTreeByPath(NodeList doc, String path) {
    NodeList n = null;
    DocumentBuilder documentBuilder = MCRDOMUtils.getDocumentBuilderUnchecked();
    try {
        // build path selection
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        XPathExpression expr = xpath.compile(path);
        // select part
        Document document = documentBuilder.newDocument();
        if (doc.item(0).getNodeName().equals("#document")) {
            // LOGGER.debug("NodeList is a document.");
            Node child = doc.item(0).getFirstChild();
            if (child != null) {
                Node node = (Node) doc.item(0).getFirstChild();
                Node imp = document.importNode(node, true);
                document.appendChild(imp);
            } else {
                document.appendChild(doc.item(0));
            }
        }
        n = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        MCRDOMUtils.releaseDocumentBuilder(documentBuilder);
    }
    return n;
}

From source file:org.n52.ses.common.environment.SESMiniServlet.java

private String createSoapFaultEnvelope(SoapFault fault) {
    Document response = XmlUtils.createDocument();

    Element soap = XmlUtils.createElement(response, SoapConstants.ENVELOPE_QNAME);
    response.appendChild(soap);//  w  w w .  j a  va  2s .co m

    Element body = XmlUtils.createElement(response, SoapConstants.BODY_QNAME);
    soap.appendChild(body);

    Element result = (Element) response.importNode(fault.toXML(), true);
    body.appendChild(result);

    return XmlUtils.toString(response);
}

From source file:org.nuxeo.common.xmap.DOMHelper.java

/**
 * Parses a string containing XML and returns a DocumentFragment containing
 * the nodes of the parsed XML.//from   w w  w.java 2s .  c  om
 */
public static void loadFragment(Element el, String fragment) {
    // Wrap the fragment in an arbitrary element
    fragment = "<fragment>" + fragment + "</fragment>";
    try {
        // Create a DOM builder and parse the fragment
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document d = factory.newDocumentBuilder().parse(new InputSource(new StringReader(fragment)));

        Document doc = el.getOwnerDocument();

        // Import the nodes of the new document into doc so that they
        // will be compatible with doc
        Node node = doc.importNode(d.getDocumentElement(), true);

        // Create the document fragment node to hold the new nodes
        DocumentFragment docfrag = doc.createDocumentFragment();

        // Move the nodes into the fragment
        while (node.hasChildNodes()) {
            el.appendChild(node.removeChild(node.getFirstChild()));
        }

    } catch (ParserConfigurationException e) {
        log.error(e, e);
    } catch (SAXException e) {
        log.error(e, e);
    } catch (IOException e) {
        log.error(e, e);
    }
}

From source file:org.obm.push.mail.ReplyEmail.java

private Element insertIntoQuoteblock(Document replyDoc, Node originalNodeToQuote) {
    originalNodeToQuote = replyDoc.importNode(originalNodeToQuote, true);

    final Element quoteBlock = replyDoc.createElement("blockquote");
    quoteBlock.setAttribute("style", "border-left:1px solid black; padding-left:1px;");
    quoteBlock.appendChild(originalNodeToQuote);
    return quoteBlock;
}

From source file:org.ojbc.bundles.adapters.staticmock.StaticMockQuery.java

private Document createFirearmRegistrationDocument(Document document, String firearmId) throws Exception {
    Document copy = createNewDocument();
    copy.appendChild(copy.importNode(document.getDocumentElement(), true));
    Node rootElement = XmlUtils.xPathNodeSearch(copy, "/*");
    LOG.debug("Keeper: " + firearmId);
    NodeList otherFirearmNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "firearm-ext:Firearm[@s:id != '" + firearmId + "']");
    for (int i = 0; i < otherFirearmNodes.getLength(); i++) {
        Node goner = otherFirearmNodes.item(i);
        LOG.debug("Goner: " + XmlUtils.xPathStringSearch(goner, "@s:id"));
        rootElement.removeChild(goner);/*  w  w w.  j a v  a 2  s.c o  m*/
    }
    NodeList otherItemRegNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "firearm-ext:ItemRegistration[@s:id != /firearm-doc:PersonFirearmRegistrationQueryResults/nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref='"
                    + firearmId + "']/nc:ItemRegistrationReference/@s:ref]");
    for (int i = 0; i < otherItemRegNodes.getLength(); i++) {
        rootElement.removeChild(otherItemRegNodes.item(i));
    }
    NodeList otherRegAssociationNodes = XmlUtils.xPathNodeListSearch(rootElement,
            "nc:PropertyRegistrationAssociation[nc:ItemReference/@s:ref != '" + firearmId + "']");
    for (int i = 0; i < otherRegAssociationNodes.getLength(); i++) {
        rootElement.removeChild(otherRegAssociationNodes.item(i));
    }
    copy.renameNode(rootElement, rootElement.getNamespaceURI(), "FirearmRegistrationQueryResults");
    Node documentRootElement = XmlUtils.xPathNodeSearch(document, "/*");
    rootElement.setPrefix(documentRootElement.getPrefix());
    return copy;
}

From source file:org.ojbc.processor.FaultableSynchronousMessageProcessor.java

Document getSoapBodyDocFromSoapEnv(Node soapEnvNode) throws Exception {

    //create convenience Document of soap body.  
    Node soapBodyNode = XmlUtils.xPathNodeSearch(soapEnvNode, "//soap:Body");
    Document soapBodyDoc = getDocBuilder().newDocument();
    Node importedSoapBodyNode = soapBodyDoc.importNode(soapBodyNode, true);
    soapBodyDoc.appendChild(importedSoapBodyNode);

    return soapBodyDoc;
}

From source file:org.ojbc.util.fedquery.entityResolution.EntityResolutionResponseHandlerAggregator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public void aggregateMergedMessageWithErrorResponses(Exchange groupedExchange) throws Exception {
    //Get the grouped exchanged consisting of the aggregated search results and merged results
    List<Exchange> grouped = groupedExchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);

    boolean responseHasErrors = false;
    Document erResponseBodyDocument = null;
    Document psResultsBeforeER = null;

    for (Exchange exchange : grouped) {
        //This is the original exchange, it contains the aggregated response message before the Person Search to ER XSLT
        if (grouped.indexOf(exchange) == 0) {
            String messageID = (String) exchange.getIn().getHeader("federatedQueryRequestGUID");

            //The new grouped exchange does not get the message headers from the original exchange so we manually copy the message ID
            groupedExchange.getIn().setHeader("federatedQueryRequestGUID", messageID);

            //Get header to see if we have error nodes.  This is the exchange before calling ER so it has these headers, subsequent exchanges do not.
            String errorResponseNodeCountString = (String) exchange.getIn().getHeader("errorResponseNodeCount");

            Integer errorResponseNodeCount = null;

            if (errorResponseNodeCountString != null) {
                errorResponseNodeCount = Integer.valueOf(errorResponseNodeCountString);
            } else {
                errorResponseNodeCount = 0;
            }/*w  ww  .  j  ava  2s  .  co m*/

            if (errorResponseNodeCount > 0) {
                responseHasErrors = true;

                if (exchange.getIn().getBody().getClass().equals("java.lang.String")) {
                    String aggregatedResponse = (String) exchange.getIn().getBody();

                    //Load up the aggregated results into a document
                    psResultsBeforeER = OJBUtils.loadXMLFromString(aggregatedResponse);

                }

                //Load up the aggregated results into a document
                psResultsBeforeER = exchange.getIn().getBody(Document.class);
            }

        }

        //This is the actual response from the ER service, it will always be exchange indexed at position 1
        else {
            //Uncomment the line below to see the individual aggregated message
            //log.debug("This is the body of the exchange in the exchange group: " + exchange.getIn().getBody());

            CxfPayload cxfPayload = (CxfPayload) exchange.getIn().getBody();
            List<Element> elementList = cxfPayload.getBody();

            erResponseBodyDocument = elementList.get(0).getOwnerDocument();
        }

    }

    //The ER service did not return with an actual response, it is down or has timed out.  Set a static error response and return.
    if (erResponseBodyDocument == null) {
        String returnMessage = MergeNotificationErrorProcessor
                .returnMergeNotificationErrorMessageEntityResolution();
        groupedExchange.getIn().setBody(returnMessage);
        return;
    }

    //If we have errors, splice them into the response
    if (responseHasErrors) {
        log.debug("Response has errors, splice them in here");

        NodeList list = psResultsBeforeER.getElementsByTagNameNS(
                "http://ojbc.org/IEPD/Extensions/SearchResultsMetadata/1.0", "SearchResultsMetadata");
        Element searchResultsMetadataElement = (Element) erResponseBodyDocument.importNode(list.item(0), true);

        Element searchResultsMetadataCollectionElement = erResponseBodyDocument.createElementNS(
                "http://nij.gov/IEPD/Exchange/EntityMergeResultMessage/1.0", "SearchResultsMetadataCollection");
        searchResultsMetadataCollectionElement.appendChild(searchResultsMetadataElement);

        erResponseBodyDocument.getFirstChild().appendChild(searchResultsMetadataCollectionElement);

    }

    //Set the response
    groupedExchange.getIn().setBody(erResponseBodyDocument);

}