Example usage for org.w3c.dom Node appendChild

List of usage examples for org.w3c.dom Node appendChild

Introduction

In this page you can find the example usage for org.w3c.dom Node appendChild.

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

From source file:org.apache.ode.utils.DOMUtils.java

/**
 * Deep clone, but don't fry, the given node in the context of the given document.
 * For all intents and purposes, the clone is the exact same copy of the node,
 * except that it might have a different owner document.
 *
 * This method is fool-proof, unlike the <code>adoptNode</code> or <code>adoptNode</code> methods,
 * in that it doesn't assume that the given node has a parent or a owner document.
 *
 * @param document/*  www . j  a v  a 2 s .c  o m*/
 * @param sourceNode
 * @return a clone of node
 */
public static Node cloneNode(Document document, Node sourceNode) {
    Node clonedNode = null;

    // what is my name?
    QName sourceQName = getNodeQName(sourceNode);
    String nodeName = sourceQName.getLocalPart();
    String namespaceURI = sourceQName.getNamespaceURI();

    // if the node is unqualified, don't assume that it inherits the WS-BPEL target namespace
    if (Namespaces.WSBPEL2_0_FINAL_EXEC.equals(namespaceURI)) {
        namespaceURI = null;
    }

    switch (sourceNode.getNodeType()) {
    case Node.ATTRIBUTE_NODE:
        if (namespaceURI == null) {
            clonedNode = document.createAttribute(nodeName);
        } else {
            String prefix = ((Attr) sourceNode).lookupPrefix(namespaceURI);
            // the prefix for the XML namespace can't be looked up, hence this...
            if (prefix == null && namespaceURI.equals(NS_URI_XMLNS)) {
                prefix = "xmlns";
            }
            // if a prefix exists, qualify the name with it
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
            }
            // create the appropriate type of attribute
            if (prefix != null) {
                clonedNode = document.createAttributeNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createAttribute(nodeName);
            }
        }
        break;
    case Node.CDATA_SECTION_NODE:
        clonedNode = document.createCDATASection(((CDATASection) sourceNode).getData());
        break;
    case Node.COMMENT_NODE:
        clonedNode = document.createComment(((Comment) sourceNode).getData());
        break;
    case Node.DOCUMENT_FRAGMENT_NODE:
        clonedNode = document.createDocumentFragment();
        break;
    case Node.DOCUMENT_NODE:
        clonedNode = document;
        break;
    case Node.ELEMENT_NODE:
        // create the appropriate type of element
        if (namespaceURI == null) {
            clonedNode = document.createElement(nodeName);
        } else {
            String prefix = namespaceURI.equals(Namespaces.XMLNS_URI) ? "xmlns"
                    : ((Element) sourceNode).lookupPrefix(namespaceURI);
            if (prefix != null && !"".equals(prefix)) {
                nodeName = prefix + ":" + nodeName;
                clonedNode = document.createElementNS(namespaceURI, nodeName);
            } else {
                clonedNode = document.createElement(nodeName);
            }
        }
        // attributes are not treated as child nodes, so copy them explicitly
        NamedNodeMap attributes = ((Element) sourceNode).getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Attr attributeClone = (Attr) cloneNode(document, attributes.item(i));
            if (attributeClone.getNamespaceURI() == null) {
                ((Element) clonedNode).setAttributeNode(attributeClone);
            } else {
                ((Element) clonedNode).setAttributeNodeNS(attributeClone);
            }
        }
        break;
    case Node.ENTITY_NODE:
        // TODO
        break;
    case Node.ENTITY_REFERENCE_NODE:
        clonedNode = document.createEntityReference(nodeName);
        // TODO
        break;
    case Node.NOTATION_NODE:
        // TODO
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        clonedNode = document.createProcessingInstruction(((ProcessingInstruction) sourceNode).getData(),
                nodeName);
        break;
    case Node.TEXT_NODE:
        clonedNode = document.createTextNode(((Text) sourceNode).getData());
        break;
    default:
        break;
    }

    // clone children of element and attribute nodes
    NodeList sourceChildren = sourceNode.getChildNodes();
    if (sourceChildren != null) {
        for (int i = 0; i < sourceChildren.getLength(); i++) {
            Node sourceChild = sourceChildren.item(i);
            Node clonedChild = cloneNode(document, sourceChild);
            clonedNode.appendChild(clonedChild);
            // if the child has a textual value, parse it for any embedded prefixes
            if (clonedChild.getNodeType() == Node.TEXT_NODE
                    || clonedChild.getNodeType() == Node.CDATA_SECTION_NODE) {
                parseEmbeddedPrefixes(sourceNode, clonedNode, clonedChild);
            }
        }
    }
    return clonedNode;
}

From source file:org.apache.ranger.utils.install.XmlConfigChanger.java

private void addProperty(String propName, String val) {
    NodeList nl = doc.getElementsByTagName(ROOT_NODE_NAME);
    Node rootConfig = nl.item(0);
    rootConfig.appendChild(createNewElement(propName, val));
}

From source file:org.apache.ranger.utils.install.XmlConfigChanger.java

private void modProperty(String propName, String val, boolean createIfNotExists) {
    Node node = findProperty(propName);
    if (node != null) {
        NodeList cnl = node.getChildNodes();
        for (int j = 0; j < cnl.getLength(); j++) {
            String nodeName = cnl.item(j).getNodeName();
            if (nodeName.equals(VALUE_NODE_NAME)) {
                if (cnl.item(j).hasChildNodes()) {
                    cnl.item(j).getChildNodes().item(0).setNodeValue(val);
                } else {
                    Node propValueNode = cnl.item(j);
                    Node txtNode = doc.createTextNode(val);
                    propValueNode.appendChild(txtNode);
                    txtNode.setNodeValue(val);
                }//  w  w  w . java2 s  .co m
                return;
            }
        }
    }
    if (createIfNotExists) {
        addProperty(propName, val);
    }
}

From source file:org.apache.ranger.utils.install.XmlConfigChanger.java

private Element createNewElement(String propName, String val) {
    Element ret = null;//from www.  j  av a2s .c  o  m

    try {
        if (doc != null) {
            ret = doc.createElement(PROPERTY_NODE_NAME);
            Node propNameNode = doc.createElement(NAME_NODE_NAME);
            Node txtNode = doc.createTextNode(propName);
            propNameNode.appendChild(txtNode);
            propNameNode.setNodeValue(propName);
            ret.appendChild(propNameNode);

            Node propValueNode = doc.createElement(VALUE_NODE_NAME);
            txtNode = doc.createTextNode(val);
            propValueNode.appendChild(txtNode);
            propValueNode.setNodeValue(propName);
            ret.appendChild(propValueNode);
        }
    } catch (Throwable t) {
        throw new RuntimeException("createNewElement(" + propName + ") with value [" + val + "] failed.", t);
    }

    return ret;
}

From source file:org.apache.servicemix.jbi.deployer.utils.ManagementSupport.java

private static Element createChild(Node parent, String name, String text) {
    Document doc = parent instanceof Document ? (Document) parent : parent.getOwnerDocument();
    Element child = doc.createElementNS(HTTP_JAVA_SUN_COM_XML_NS_JBI_MANAGEMENT_MESSAGE, name);
    if (text != null) {
        child.appendChild(doc.createTextNode(text));
    }/*ww  w  . ja v  a  2s  .  c o m*/
    parent.appendChild(child);
    return child;
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

protected void injectOnLoadHandlers(Node bodyTag) {
    Element onloadScript = bodyTag.getOwnerDocument().createElement("script");
    bodyTag.appendChild(onloadScript);
    onloadScript.appendChild(bodyTag.getOwnerDocument().createTextNode("gadgets.util.runOnLoadHandlers();"));
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects message bundles into the gadget output.
 * @throws GadgetException If we are unable to retrieve the message bundle.
 *//*from www .j  a  v a  2s.  c  o  m*/
protected void injectMessageBundles(MessageBundle bundle, Node scriptTag) throws GadgetException {
    String msgs = bundle.toJSONString();

    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setMessages_(");
    text.appendData(msgs);
    text.appendData(");");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects default values for user prefs into the gadget output.
 *//*from  w ww  .  j ava  2 s .c o  m*/
protected void injectDefaultPrefs(Gadget gadget, Node scriptTag) {
    Collection<UserPref> prefs = gadget.getSpec().getUserPrefs().values();
    Map<String, String> defaultPrefs = Maps.newHashMapWithExpectedSize(prefs.size());
    for (UserPref up : prefs) {
        defaultPrefs.put(up.getName(), up.getDefaultValue());
    }
    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setDefaultPrefs_(");
    text.appendData(JsonSerializer.serialize(defaultPrefs));
    text.appendData(");");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects preloads into the gadget output.
 *
 * If preloading fails for any reason, we just output an empty object.
 *//*  www .j a  v a2s. co  m*/
protected void injectPreloads(Gadget gadget, Node scriptTag) {
    List<Object> preload = Lists.newArrayList();
    for (PreloadedData preloaded : gadget.getPreloads()) {
        try {
            preload.addAll(preloaded.toJson());
        } catch (PreloadException pe) {
            // This will be thrown in the event of some unexpected exception. We can move on.
            LOG.log(Level.WARNING, "Unexpected error when preloading", pe);
        }
    }
    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.io.preloaded_=");
    text.appendData(JsonSerializer.serialize(preload));
    text.appendData(";");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.servlet.CajaContentRewriter.java

public void rewrite(Gadget gadget, MutableContent mc) {
    if (!cajaEnabled(gadget))
        return;//from ww  w  .j a v a  2s  .c o  m

    GadgetContext gadgetContext = gadget.getContext();
    boolean debug = gadgetContext.getDebug();
    Document doc = mc.getDocument();

    // Serialize outside of MutableContent, to prevent a re-parse.
    String docContent = HtmlSerialization.serialize(doc);
    String cacheKey = HashUtil.checksum(docContent.getBytes());
    Node root = doc.createDocumentFragment();
    root.appendChild(doc.getDocumentElement());

    Node cajoledData = null;
    if (cajoledCache != null && !debug) {
        Element cajoledOutput = cajoledCache.getElement(cacheKey);
        if (cajoledOutput != null) {
            cajoledData = doc.adoptNode(cajoledOutput);
            createContainerFor(doc, cajoledData);
            mc.documentChanged();
        }
    }

    if (cajoledData == null) {
        UriFetcher fetcher = makeFetcher(gadget);
        UriPolicy policy = makePolicy(gadget);
        URI javaGadgetUri = gadgetContext.getUrl().toJavaUri();
        MessageQueue mq = new SimpleMessageQueue();
        MessageContext context = new MessageContext();
        PluginMeta meta = new PluginMeta(fetcher, policy);
        PluginCompiler compiler = makePluginCompiler(meta, mq);

        compiler.setMessageContext(context);

        if (debug) {
            // This will load cajita-debugmode.js
            gadget.addFeature("caja-debug");
            compiler.setGoals(compiler.getGoals().without(PipelineMaker.ONE_CAJOLED_MODULE)
                    .with(PipelineMaker.ONE_CAJOLED_MODULE_DEBUG));
        }

        InputSource is = new InputSource(javaGadgetUri);
        boolean safe = false;

        compiler.addInput(new Dom(root), javaGadgetUri);

        try {
            if (!compiler.run()) {
                throw new GadgetRewriteException("Gadget has compile errors");
            }
            StringBuilder scriptBody = new StringBuilder();
            CajoledModule cajoled = compiler.getJavascript();
            TokenConsumer tc = debug ? new JsPrettyPrinter(new Concatenator(scriptBody))
                    : new JsMinimalPrinter(new Concatenator(scriptBody));
            cajoled.render(new RenderContext(tc).withAsciiOnly(true).withEmbeddable(true));

            tc.noMoreTokens();

            Node html = compiler.getStaticHtml();

            Element script = doc.createElementNS(Namespaces.HTML_NAMESPACE_URI, "script");
            script.setAttributeNS(Namespaces.HTML_NAMESPACE_URI, "type", "text/javascript");
            script.appendChild(doc.createTextNode(scriptBody.toString()));

            Element cajoledOutput = doc.createElement("div");
            cajoledOutput.setAttribute("id", "cajoled-output");
            cajoledOutput.setAttribute("classes", "g___");
            cajoledOutput.setAttribute("style", "position: relative;");

            cajoledOutput.appendChild(doc.adoptNode(html));
            cajoledOutput.appendChild(tameCajaClientApi(doc));
            cajoledOutput.appendChild(doc.adoptNode(script));

            Element messagesNode = formatErrors(doc, is, docContent, mq, /* is invisible */ false);
            cajoledOutput.appendChild(messagesNode);
            if (cajoledCache != null && !debug) {
                cajoledCache.addElement(cacheKey, cajoledOutput);
            }

            cajoledData = cajoledOutput;
            createContainerFor(doc, cajoledData);
            mc.documentChanged();
            safe = true;
            HtmlSerialization.attach(doc, htmlSerializer, null);
        } catch (GadgetRewriteException e) {
            // There were cajoling errors
            // Content is only used to produce useful snippets with error messages
            createContainerFor(doc, formatErrors(doc, is, docContent, mq, true /* visible */));
            logException(e, mq);
            safe = true;
        } finally {
            if (!safe) {
                // Fail safe
                mc.setContent("");
            }
        }
    }
}