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:fr.imag.model2roo.addon.polyglot.PolyglotOperationsImpl.java

/** {@inheritDoc} */
public void configureRest() {
    Element webConfig;//w w  w  .j a v a2s . c  o m
    String webConfigPath;
    List<Element> addedBeans;
    Document webConfigDocument;

    // Add required dependencies
    projectOperations.addDependencies("", this.getDependencies("/configuration/addDependencies"));

    // Add json view resolver
    webConfigPath = pathResolver.getFocusedIdentifier(Path.SRC_MAIN_WEBAPP, "WEB-INF/spring/webmvc-config.xml");
    webConfigDocument = XmlUtils.readXml(fileManager.getInputStream(webConfigPath));
    webConfig = webConfigDocument.getDocumentElement();

    addedBeans = XmlUtils.findElements("/configuration/addBeans/bean",
            XmlUtils.getConfiguration(this.getClass()));
    for (Element element : addedBeans) {
        webConfig.appendChild(webConfigDocument.importNode(element, true));
    }

    fileManager.createOrUpdateTextFileIfRequired(webConfigPath, XmlUtils.nodeToString(webConfigDocument),
            false);
}

From source file:com.betfair.testing.utils.cougar.helpers.CougarHelpers.java

private Document handleSoapResponse(SOAPMessage response, HttpResponseBean responseBean)
        throws TransformerException, SOAPException, ParserConfigurationException {

    Node responseNode = null;/*w ww  . j a  v a2 s .  co  m*/

    if (response != null) {
        responseNode = extractResponseNode(response);
        extractHeaderDataSOAP(response, responseBean);
    }

    // build new xml document for assertion
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document newDocument = builder.newDocument();

    Node adoptedBlob = newDocument.importNode(responseNode, true);
    newDocument.appendChild(adoptedBlob);

    // Output as String if required
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    transformer.transform(new DOMSource(newDocument), new StreamResult(out));

    if (logger.isDebugEnabled()) {
        logger.debug("\n Return Doc \n");
        logger.debug(new String(out.toByteArray()));
    }

    return newDocument;
}

From source file:com.collabnet.tracker.core.PTrackerWebServicesClient.java

/**
 * Get the next page of results.  This is used by the ClientArtifactListXMLHelper
 * to ensure that all results are returned
 * @param pageInfo//w  w w .jav a2s  .  c  om
 * @return
 * @throws Exception
 */
public Document getNextPage(Node pageInfo, String altQueryRef) throws Exception {
    validateNextPage(pageInfo, altQueryRef);
    EngineConfiguration config = mClient.getEngineConfiguration();
    DispatcherService service = new DispatcherServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/ws/Dispatcher");
    Dispatcher theService = service.getDispatcher(portAddress);

    Document doc = createNewXMLDocument(DEFAULT_NAMESPACE, "ns1:" + "getNextPage");
    Element root = doc.getDocumentElement();
    Node newPageInfo = doc.importNode(pageInfo, true);
    root.appendChild(newPageInfo);

    TrackerUtil.debug("getNextPage()");
    Response r = theService.execute(toRequest(doc));
    Document result = toDocument(r);

    return result;
}

From source file:com.enonic.vertical.adminweb.ContentObjectHandlerServlet.java

private void addStyleSheet(Element contentobjectElem, String elemName, ResourceKey styleSheetKey)
        throws VerticalAdminException {

    ResourceFile resource = resourceService.getResourceFile(styleSheetKey);
    if (resource == null) {
        throw new StylesheetNotFoundException(styleSheetKey);
    }//from  w  w w . j  av  a2s .co  m
    Document styleSheetDoc;
    try {
        styleSheetDoc = resource.getDataAsXml().getAsDOMDocument();
    } catch (XMLException e) {
        throw new InvalidStylesheetException(styleSheetKey, e);
    }

    Element styleSheetRoot = styleSheetDoc.getDocumentElement();
    String attr = styleSheetRoot.getAttribute("xmlns:xsl");
    styleSheetRoot.removeAttribute("xmlns:xsl");
    styleSheetRoot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsl", attr);
    Document doc = contentobjectElem.getOwnerDocument();
    Element elem = XMLTool.createElement(doc, contentobjectElem, elemName);
    elem.appendChild(doc.importNode(styleSheetRoot, true));
}

From source file:org.alfresco.web.config.forms.FormConfigRuntime.java

/**
 * @param element//from w ww.  jav a 2 s  .  c om
 * @return
 * @throws ParserConfigurationException
 */
public org.dom4j.Element convert(org.w3c.dom.Element element) throws ParserConfigurationException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    org.w3c.dom.Document doc1 = builder.newDocument();
    doc1.appendChild(doc1.importNode(element, true));
    // Convert w3c document to dom4j document
    org.dom4j.io.DOMReader reader = new org.dom4j.io.DOMReader();
    org.dom4j.Document doc2 = reader.read(doc1);

    return doc2.getRootElement();
}

From source file:com.bstek.dorado.view.config.XmlDocumentPreprocessor.java

@SuppressWarnings("unchecked")
private void postProcessNodeReplacement(Element element) {
    Document ownerDocument = element.getOwnerDocument();
    Node child = element.getFirstChild();
    while (child != null) {
        Node nextChild = child.getNextSibling();
        if (child instanceof Element) {
            if (child.getUserData("dorado.delete") != null) {
                List<Element> replaceContent = (List<Element>) child.getUserData("dorado.replace");
                if (replaceContent != null) {
                    for (Element el : replaceContent) {
                        Element clonedElement = (Element) ownerDocument.importNode(el, true);
                        element.insertBefore(clonedElement, child);
                    }//from  w ww . j av  a 2 s. c om
                    child.setUserData("dorado.replace", null, null);
                }
                element.removeChild(child);
                child.setUserData("dorado.delete", null, null);
            }
        }
        child = nextChild;
    }
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void execute0(Document document, MessageContext msgCtxt) throws Exception {
    String xpath = getXpath(msgCtxt);
    XPathEvaluator xpe = getXpe(msgCtxt);
    NodeList nodes = (NodeList) xpe.evaluate(xpath, document, XPathConstants.NODESET);
    validate(nodes);/*  w  w w.jav a  2 s  . c om*/
    EditAction action = getAction(msgCtxt);
    if (action == EditAction.Remove) {
        remove(nodes);
        return;
    }

    short newNodeType = getNewNodeType(msgCtxt);
    String text = getNewNodeText(msgCtxt);
    Node newNode = null;
    switch (newNodeType) {
    case Node.ELEMENT_NODE:
        // Create a duplicate node and transfer ownership of the
        // new node into the destination document.
        Document temp = XmlUtils.parseXml(text);
        newNode = document.importNode(temp.getDocumentElement(), true);
        break;
    case Node.ATTRIBUTE_NODE:
        if (text.indexOf("=") < 1) {
            throw new IllegalStateException("attribute spec must be name=value");
        }
        String[] parts = text.split("=", 2);
        if (parts.length != 2)
            throw new IllegalStateException("attribute spec must be name=value");
        Attr attr = document.createAttribute(parts[0]);
        attr.setValue(parts[1]);
        newNode = attr;
        break;
    case Node.TEXT_NODE:
        newNode = document.createTextNode(text);
        break;
    }
    switch (action) {
    case InsertBefore:
        insertBefore(nodes, newNode, newNodeType);
        break;
    case Append:
        append(nodes, newNode, newNodeType);
        break;
    case Replace:
        replace(nodes, newNode, newNodeType);
        break;
    }
}

From source file:SVGJUnitTest.java

@Test
public void mergeAll() throws IOException, TranscoderException {
    File dir = new File("target/");
    String parser = XMLResourceDescriptor.getXMLParserClassName();
    SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
    Document doc = null;
    if (dir.isDirectory()) {
        File[] listOfFiles = dir.listFiles();

        for (File file : listOfFiles) {
            if (file.getName().endsWith(".svg")) {
                System.out.println("File: " + file.getName());
                if (doc == null) {

                    String data = FileUtils.readFileToString(new File("target/" + file.getName()), "UTF-8");
                    InputStream inputStream = new ByteArrayInputStream(data.getBytes());
                    doc = f.createDocument("http://www.w3.org/2000/svg", inputStream);
                } else {
                    String data = FileUtils.readFileToString(new File("target/" + file.getName()), "UTF-8");
                    InputStream inputStream = new ByteArrayInputStream(data.getBytes());
                    Document doc2 = f.createDocument("http://www.w3.org/2000/svg", inputStream);
                    Node n = doc.importNode(doc2.getDocumentElement(), true);
                    doc.getDocumentElement().appendChild(n);
                }// w ww  .j a  v  a  2 s. c  o  m
            }

        }

    }
    if (doc != null) {
        PNGTranscoder t = new PNGTranscoder();

        TranscoderInput input = new TranscoderInput(doc);

        OutputStream ostream = new FileOutputStream("target/" + new Date().getTime() + "-snapshot.png");
        TranscoderOutput output = new TranscoderOutput(ostream);

        // Perform the transcoding.
        t.transcode(input, output);
        ostream.flush();
        ostream.close();

    }

}

From source file:de.mpg.escidoc.services.common.util.Util.java

/**
  * Execute the GET-method.//from   ww  w .  j  av a2 s . co m
  * @param client
  * @param queryUrl
  * @param documentBuilder
  * @param document
  * @param element
  * @return true if the array contains the format object, else false
  */
private static void executeGetMethod(HttpClient client, String queryUrl, DocumentBuilder documentBuilder,
        Document document, Element element) {
    String previousUrl = null;
    try {
        GetMethod method = new GetMethod(queryUrl);
        ProxyHelper.executeMethod(client, method);
        logger.info("queryURL from executeGetMethod  " + queryUrl);

        if (method.getStatusCode() == 200) {
            String[] results = method.getResponseBodyAsString().split("\n");
            for (String result : results) {
                if (!"".equals(result.trim())) {
                    String detailsUrl = result.split("\\|")[1];
                    // if there is an alternative name, take only the first occurrence
                    if (!detailsUrl.equalsIgnoreCase(previousUrl)) {
                        GetMethod detailMethod = new GetMethod(detailsUrl + "?format=rdf");
                        previousUrl = detailsUrl;

                        logger.info(detailMethod.getPath());
                        logger.info(detailMethod.getQueryString());

                        ProxyHelper.setProxy(client, detailsUrl);
                        client.executeMethod(detailMethod);
                        if (detailMethod.getStatusCode() == 200) {
                            Document details = documentBuilder.parse(detailMethod.getResponseBodyAsStream());
                            element.appendChild(document.importNode(details.getFirstChild(), true));
                        } else {
                            logger.error("Error querying CoNE: Status " + detailMethod.getStatusCode() + "\n"
                                    + detailMethod.getResponseBodyAsString());
                        }
                    }
                }
            }

        } else {
            logger.error("Error querying CoNE: Status " + method.getStatusCode() + "\n"
                    + method.getResponseBodyAsString());
        }
    } catch (Exception e) {
        logger.error("Error querying CoNE service. This is normal during unit tests. "
                + "Otherwise it should be clarified if any measures have to be taken.");
    }
}

From source file:com.enonic.vertical.adminweb.handlers.xmlbuilders.ContentBaseXMLBuilder.java

/**
 * <p> A generic method that builds the contentdata block of arbitrary depth. All fields starting with the pattern 'contentdata_foo' and
 * followed by arbitrary patterns like '_bar' are translated to nested xml elements, where 'foo' and 'bar' is the name of the elements.
 * The last element can be specified with one of the following prefix and suffixes: <ul> <li>@      (prefix) - element text will be set
 * as an attribute to the parent element <li>_CDATA (suffix) - element text will be wrapped in a CDATA element <li>_XHTML (suffix) -
 * element text will be turned into XHTML elements </ul> When reaching one of the prefix and suffixes, the element creating process will
 * terminate for this field. </p> <p/> <p>Elements already created with the same path will be reused.</p> <p/> <p>Example:<br> The key
 * 'contentdata_foo_bar_zot_CDATA' with the value '<b>alpha</b>' will transform into the following xml:
 * <pre>//from  w  w  w  .  j av a2s. c  o m
 * &lt;contentdata&gt;
 *   &lt;foo&gt;
 *     &lt;bar&gt;
 *       &lt;zot&gt;
 *         &lt;[!CDATA[&lt;b&gt;alpha&lt;/b&gt;]]&gt;
 *       &lt;/zot&gt;
 *     &lt;/bar&gt;
 *   &lt;/foo&gt;
 * &lt;/contentdata&gt;
 * </pre>
 * </p>
 */
public void buildContentTypeXML(User user, Document doc, Element contentdata, ExtendedMap formItems)
        throws VerticalAdminException {
    for (Object o : formItems.keySet()) {
        String key = (String) o;
        StringTokenizer keyTokenizer = new StringTokenizer(key, "_");

        if ("contentdata".equals(keyTokenizer.nextToken())) {
            Element root = contentdata;
            while (keyTokenizer.hasMoreTokens()) {
                String keyToken = keyTokenizer.nextToken();
                if ("CDATA".equals(keyToken)) {
                    XMLTool.createCDATASection(doc, root, formItems.getString(key));
                    break;
                } else if ("XML".equals(keyToken)) {
                    String xmlDoc = formItems.getString(key);
                    Document tempDoc = XMLTool.domparse(xmlDoc);
                    root.appendChild(doc.importNode(tempDoc.getDocumentElement(), true));
                    break;
                } else if ("XHTML".equals(keyToken)) {
                    XMLTool.createXHTMLNodes(doc, root, formItems.getString(key), true);
                    break;
                } else if (keyToken.charAt(0) == '@') {
                    root.setAttribute(keyToken.substring(1), formItems.getString(key));
                    break;
                } else {
                    Element elem = XMLTool.getElement(root, keyToken);
                    if (elem == null) {
                        root = XMLTool.createElement(doc, root, keyToken);
                    } else {
                        root = elem;
                    }
                    if (!keyTokenizer.hasMoreTokens()) {
                        XMLTool.createTextNode(doc, root, formItems.getString(key));
                        break;
                    }
                }
            }
        }
    }
}