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:com.adaptris.util.XmlUtils.java

/**
 * Convenience method which enables a new Node to be added to a parent at a specified position, by specifying the Node to insert
 * before. Here is a sample of how to use:
 * /*from   w ww.j  av a2 s . c  o m*/
 * <pre>
*  {@code 
 *
 *   // Example of how to insert a Node as the 3rd child of a parent
 *   Node p  = xmlUtils.getSingleNode("/mydoc/parent");
 *   Node c   = xmlUtils.getSingleNode("/mydoc/parent/child[4]");
 *   Node n = // Node creation code here;
 *   xmlUtils.insertNodeBefore(newNode, child, parent);
 *
 * }
 * </pre>
 * 
 * @param newNode the Node to be added
 * @param existingNode the Node to insert before
 * @param parent the parent Node
 * @throws Exception on error.
 */
public void insertNodeBefore(Node newNode, Node existingNode, Node parent) throws Exception {
    Document parentDoc = parent.getOwnerDocument();
    Document newDoc = newNode.getOwnerDocument();
    Node nodeToAdd = newNode;
    if (!parentDoc.equals(newDoc)) {
        nodeToAdd = parentDoc.importNode(newNode, true);
    }

    parent.insertBefore(nodeToAdd, existingNode);
}

From source file:com.enonic.esl.xml.XMLTool.java

/**
 * Create XML/XHTML nodes in a XML DOM from a HTML string. All
 * nodes inside the body tag are then inserted in the document passed as parameter.
 *
 * @param doc       The owner document./*from ww  w.  j av a  2 s.c o  m*/
 * @param root      The element the nodes should be created below.
 * @param html      The html code that should be inserted as nodes.
 * @param tidyFirst Tidy up the document before creating the nodes.
 */
public static void createXHTMLNodes(Document doc, Element root, String html, boolean tidyFirst) {
    if (html == null) {
        return;
    }

    if (tidyFirst) {
        html = tidy(html);
    }

    html = html.trim();
    if (html.length() == 0) {
        return;
    }

    Document xhtml = domparse(html);

    NodeList xhtmlTags = xhtml.getElementsByTagName("body").item(0).getChildNodes();

    for (int i = 0; i < xhtmlTags.getLength(); i++) {
        root.appendChild(doc.importNode(xhtmlTags.item(i), true));
    }
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * returns the initial instance/*from ww w.  ja  va  2 s .  c o m*/
 * @return the initial instance
 */
public Document getInitialInstance() {
    if (this.initialInstance != null) {
        Document doc = DOMUtil.newDocument(true, false);
        doc.appendChild(doc.importNode(this.initialInstance, true));
        return doc;
    } else {
        return null;
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Transform into formatted XML./*from   ww w . j a v  a2s  .c o  m*/
 */
private String getFormattedXml(Node node) {
    Document document = node.getOwnerDocument().getImplementation().createDocument("", "fake", null);
    Element copy = (Element) document.importNode(node, true);
    document.importNode(node, false);
    document.removeChild(document.getDocumentElement());
    document.appendChild(copy);
    DOMImplementation domImpl = document.getImplementation();
    DOMImplementationLS domImplLs = (DOMImplementationLS) domImpl.getFeature("LS", "3.0");
    LSSerializer serializer = domImplLs.createLSSerializer();
    serializer.getDomConfig().setParameter("format-pretty-print", true);
    return serializer.writeToString(document);
}

From source file:com.msopentech.odatajclient.engine.data.AbstractODataBinder.java

protected Element toPrimitivePropertyElement(final String name, final ODataPrimitiveValue value,
        final Document doc, final boolean setType) {

    final Element element = doc.createElement(ODataConstants.PREFIX_DATASERVICES + name);
    if (setType) {
        element.setAttribute(ODataConstants.ATTR_M_TYPE, value.getTypeName());
    }/*from  ww  w .  j  a v  a  2  s.c o m*/

    if (value instanceof ODataGeospatialValue) {
        element.appendChild(doc.importNode(((ODataGeospatialValue) value).toTree(), true));
    } else {
        element.setTextContent(value.toString());
    }

    return element;
}

From source file:de.betterform.xml.xforms.model.Instance.java

/**
 * Returns a new created instance document.
 * <p/>// ww  w.  j  a  v a  2 s  .  c  om
 * If this instance has an original instance, it will be imported into this
 * new document. Otherwise the new document is left empty.
 *
 * @return a new created instance document.
 * @throws de.betterform.xml.xforms.exception.XFormsException
 */
private Document createInstanceDocument() throws XFormsException {
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);
        factory.setValidating(false);
        Document document = factory.newDocumentBuilder().newDocument();

        if (this.initialInstance != null) {
            Node imported = document.importNode(this.initialInstance.cloneNode(true), true);
            document.appendChild(imported);

            if (getXFormsAttribute(SRC_ATTRIBUTE) == null && getXFormsAttribute(RESOURCE_ATTRIBUTE) == null) {
                NamespaceResolver.applyNamespaces(this.element, document.getDocumentElement());
            }
        }

        return document;
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:com.enonic.vertical.engine.handlers.ContentObjectHandler.java

public void updateContentObject(Document doc) throws VerticalUpdateException {
    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {//from w ww  .  j a va2 s .com
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_UPDATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key = -1, menuKey = -1;
            ResourceKey styleSheetKey = null, borderStyleSheetKey = null;

            pos = 0;
            tmpStr = root.getAttribute("key");
            if (tmpStr != null && tmpStr.length() > 0) {
                key = Integer.parseInt(tmpStr);
            } else {
                String message = "No content object key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = new ResourceKey(tmpStr);
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = new ResourceKey(tmpStr);
                }
            }

            // element: name
            String name = null;
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            byte[] contentobjectdata;
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(7, key);
            preparedStmt.setInt(1, menuKey);
            if (styleSheetKey != null) {
                preparedStmt.setString(2, styleSheetKey.toString());
            } else {
                preparedStmt.setNull(2, Types.VARCHAR);
            }
            if (borderStyleSheetKey != null) {
                preparedStmt.setString(3, borderStyleSheetKey.toString());
            } else {
                preparedStmt.setNull(3, Types.VARCHAR);
            }
            preparedStmt.setCharacterStream(4, new StringReader(name), name.length());
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(5, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(5, Types.VARCHAR);
            }

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(6, runAs.getKey());

            // update content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to update content object, no content object updated.";
                VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to update content object(s): %t";
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorUpdate(this.getClass(), 0, message, msgData, nfe);
    } finally {
        close(preparedStmt);
        close(con);
    }
}

From source file:com.enonic.vertical.engine.handlers.ContentObjectHandler.java

public int[] createContentObject(CopyContext copyContext, Document doc, boolean useOldKey)
        throws VerticalCreateException {

    Element docElem = doc.getDocumentElement();
    Element[] contentobjectElems;
    if ("contentobject".equals(docElem.getTagName())) {
        contentobjectElems = new Element[] { docElem };
    } else {/*from w w  w.  ja v  a  2  s  .  c  om*/
        contentobjectElems = XMLTool.getElements(doc.getDocumentElement());
    }

    Connection con = null;
    PreparedStatement preparedStmt = null;
    int pos = 0;
    String tmpStr = null;
    TIntArrayList newKeys = new TIntArrayList();

    try {
        con = getConnection();
        preparedStmt = con.prepareStatement(COB_CREATE);

        for (Element root : contentobjectElems) {
            Map subelems = XMLTool.filterElements(root.getChildNodes());

            int key, menuKey = -1;
            String styleSheetKey = "", borderStyleSheetKey = "";

            pos = 0;
            String keyStr = root.getAttribute("key");
            if (!useOldKey || tmpStr == null || tmpStr.length() == 0) {
                key = getNextKey(COB_TABLE);
            } else {
                key = Integer.parseInt(tmpStr);
            }
            if (copyContext != null) {
                copyContext.putContentObjectKey(Integer.parseInt(keyStr), key);
            }
            newKeys.add(key);

            pos++;
            // was sitekey

            pos++;
            tmpStr = root.getAttribute("menukey");
            if (tmpStr != null && tmpStr.length() > 0) {
                menuKey = Integer.parseInt(tmpStr);
            } else {
                String message = "No menu key specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            Element subelem = (Element) subelems.get("objectstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    styleSheetKey = tmpStr;
                } else {
                    String message = "No object stylesheet key specified.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No object stylesheet specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            pos++;
            subelem = (Element) subelems.get("borderstylesheet");
            if (subelem != null) {
                tmpStr = subelem.getAttribute("key");
                if (tmpStr != null && tmpStr.length() > 0) {
                    borderStyleSheetKey = tmpStr;
                }
            }

            String name = null;
            byte[] contentobjectdata;

            // element: name
            subelem = (Element) subelems.get("name");
            if (subelem != null) {
                name = XMLTool.getElementText(subelem);
                if (name == null || name.length() == 0) {
                    String message = "Empty stylesheet name.";
                    VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
                }
            } else {
                String message = "No stylesheet name specified.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }

            // element: contentobjectdata (optional)
            subelem = (Element) subelems.get("contentobjectdata");
            if (subelem != null) {
                Document codDoc = XMLTool.createDocument();
                codDoc.appendChild(codDoc.importNode(subelem, true));
                contentobjectdata = XMLTool.documentToBytes(codDoc, "UTF-8");
            } else {
                contentobjectdata = null;
            }

            preparedStmt.setInt(1, key);
            preparedStmt.setInt(2, menuKey);
            preparedStmt.setString(3, styleSheetKey);
            if (borderStyleSheetKey.length() > 0) {
                preparedStmt.setString(4, borderStyleSheetKey);
            } else {
                preparedStmt.setNull(4, Types.VARCHAR);
            }
            preparedStmt.setString(5, name);
            if (contentobjectdata != null) {
                preparedStmt.setBinaryStream(6, new ByteArrayInputStream(contentobjectdata),
                        contentobjectdata.length);
            } else {
                preparedStmt.setNull(6, Types.VARBINARY);
            }

            RunAsType runAs = RunAsType.INHERIT;
            String runAsStr = root.getAttribute("runAs");
            if (StringUtils.isNotEmpty(runAsStr)) {
                runAs = RunAsType.valueOf(runAsStr);
            }
            preparedStmt.setInt(7, runAs.getKey());

            // create content object
            int result = preparedStmt.executeUpdate();
            if (result <= 0) {
                String message = "Failed to create content object, no content object created.";
                VerticalEngineLogger.errorCreate(this.getClass(), 0, message, null);
            }
        }

        preparedStmt.close();
        preparedStmt = null;
    } catch (SQLException sqle) {
        String message = "Failed to create content object(s): %t";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, sqle);
    } catch (NumberFormatException nfe) {
        String message = "Failed to parse %0: %1";
        Object[] msgData;
        switch (pos) {
        case 1:
            msgData = new Object[] { "site key", tmpStr };
            break;
        case 2:
            msgData = new Object[] { "menu key", tmpStr };
            break;
        case 3:
            msgData = new Object[] { "object stylesheet key", tmpStr };
            break;
        case 4:
            msgData = new Object[] { "border stylesheet key", tmpStr };
            break;
        default:
            msgData = new Object[] { "content object key", tmpStr };
        }
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, msgData, nfe);
    } catch (VerticalKeyException gke) {
        String message = "Failed to generate content object key";
        VerticalEngineLogger.errorCreate(this.getClass(), 0, message, gke);
    } finally {
        close(preparedStmt);
        close(con);
    }

    return newKeys.toArray();
}

From source file:de.betterform.xml.xforms.XFormsProcessorImpl.java

private Document toDocument(Node node) throws XFormsException {
    // ensure xerces dom
    if (node instanceof Document) {
        return (Document) node;
    }//w  ww .  j ava 2  s  .co  m

    Document document = getDocumentBuilder().newDocument();
    if (node instanceof Document) {
        node = ((Document) node).getDocumentElement();
    }
    document.appendChild(document.importNode(node, true));

    return document;
}

From source file:ddf.catalog.source.opensearch.CddaOpenSearchSite.java

/**
 * @param is/*from   w  w w  .ja  va  2s. c  o m*/
 * @param queryRequest
 * @return
 * @throws UnsupportedQueryException
 */
private SourceResponseImpl processResponse(InputStream is, QueryRequest queryRequest)
        throws ConversionException {
    List<Result> resultQueue = new ArrayList<Result>();
    Document atomDoc = null;

    try {
        atomDoc = OpenSearchSiteUtil.convertStreamToDocument(is);
        if (logger.isDebugEnabled()) {
            logger.debug("Incoming response from OpenSearch site: " + XPathHelper.xmlToString(atomDoc));
        }
    } finally {
        IOUtils.closeQuietly(is);
    }

    Map<String, String> securityProps = updateDefaultClassification();

    Document ddmsDoc = OpenSearchSiteUtil.normalizeAtomToDDMS(tf, atomDoc, normalizeXslt, securityProps);

    if (logger.isDebugEnabled()) {
        logger.debug("Incoming response from OpenSearch site normalized to DDMS: "
                + XPathHelper.xmlToString(ddmsDoc));
    }
    NodeList list = ddmsDoc.getElementsByTagNameNS("http://metadata.dod.mil/mdr/ns/DDMS/2.0/", "Resource");

    String resultNum = evaluate("//opensearch:totalResults", atomDoc);
    long totalResults = 0;
    if (resultNum != null && !resultNum.isEmpty()) {
        totalResults = Integer.parseInt(resultNum);
    } else {
        // if no openseach:totalResults element, spec says to use list
        // of current items as totalResults
        totalResults = list.getLength();
    }

    // offset always comes in as 0 from DDF federation logic
    for (int i = 0; i < list.getLength(); i++) {
        try {
            Node curNode = list.item(i);
            String relevance = OpenSearchSiteUtil.popAttribute(curNode, "score");
            String id = OpenSearchSiteUtil.popAttribute(curNode, "id");
            String date = OpenSearchSiteUtil.popAttribute(curNode, "date");
            Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            doc.appendChild(doc.importNode(curNode, true));

            if (logger.isDebugEnabled()) {
                logger.debug(XPathHelper.xmlToString(doc));
            }
            resultQueue.add(createResponse(doc, id, date, relevance));
        } catch (ParserConfigurationException pce) {
            throw new ConversionException("Couldn't convert node to document. ", pce);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Returning " + list.getLength() + " entries in response.");
        }
    }

    SourceResponseImpl response = new SourceResponseImpl(queryRequest, resultQueue);
    response.setHits(totalResults);

    return response;
}