Example usage for org.w3c.dom Node insertBefore

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

Introduction

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

Prototype

public Node insertBefore(Node newChild, Node refChild) throws DOMException;

Source Link

Document

Inserts the node newChild before the existing child node refChild.

Usage

From source file:org.apache.shindig.gadgets.parse.nekohtml.NekoSimplifiedHtmlParser.java

private void fixNekoWeirdness(Document document) {
    // Neko as of versions > 1.9.13 stuffs all leading <script> nodes into <head>.
    // This breaks all sorts of assumptions in gadgets, notably the existence of document.body.
    // We can't tell Neko to avoid putting <script> into <head> however, since gadgets
    // like <Content><script>...</script><style>...</style> will break due to both
    // <script> and <style> ending up in <body> -- at which point Neko unceremoniously
    // drops the <style> (and <link>) elements.
    // Therefore we just search for <script> elements in <head> and stuff them all into
    // the top of <body>.
    // This method assumes a normalized document as input.
    Node html = DomUtil.getFirstNamedChildNode(document, "html");
    if (html.getNextSibling() != null && html.getNextSibling().getNodeName().equalsIgnoreCase("html")) {
        // if a doctype is specified, then the desired root <html> node is wrapped by an <HTML> node
        // Pull out the <html> root.
        html = html.getNextSibling();/*ww  w. ja v a2  s.  c  om*/
    }
    Node head = DomUtil.getFirstNamedChildNode(html, "head");
    if (head == null) {
        head = document.createElement("head");
        html.insertBefore(head, html.getFirstChild());
    }
    NodeList headNodes = head.getChildNodes();
    Stack<Node> headScripts = new Stack<Node>();
    for (int i = 0; i < headNodes.getLength(); ++i) {
        Node headChild = headNodes.item(i);
        if (headChild.getNodeName().equalsIgnoreCase("script")) {
            headScripts.add(headChild);
        }
    }

    // Remove from head, add to top of <body> in <head> order.
    Node body = DomUtil.getFirstNamedChildNode(html, "body");
    if (body == null) {
        body = document.createElement("body");
        html.insertBefore(body, head.getNextSibling());
    }
    Node bodyFirst = body.getFirstChild();
    while (!headScripts.isEmpty()) {
        Node headScript = headScripts.pop();
        head.removeChild(headScript);
        body.insertBefore(headScript, bodyFirst);
        bodyFirst = headScript;
    }
}

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

protected void injectBaseTag(Gadget gadget, Node headTag) {
    GadgetContext context = gadget.getContext();
    if (containerConfig.getBool(context.getContainer(), INSERT_BASE_ELEMENT_KEY)) {
        Uri base = gadget.getSpec().getUrl();
        View view = gadget.getCurrentView();
        if (view != null && view.getHref() != null) {
            base = view.getHref();// ww w . j ava2  s .co  m
        }
        Element baseTag = headTag.getOwnerDocument().createElement("base");
        baseTag.setAttribute("href", base.toString());
        headTag.insertBefore(baseTag, headTag.getFirstChild());
    }
}

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

protected void injectGadgetBeacon(Gadget gadget, Node headTag, Node firstHeadChild) throws GadgetException {
    Element beaconNode = headTag.getOwnerDocument().createElement("script");
    beaconNode.setTextContent(IS_GADGET_BEACON);
    headTag.insertBefore(beaconNode, firstHeadChild);
}

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

/**
 * Injects javascript libraries needed to satisfy feature dependencies.
 *//*from www  .jav  a  2 s  . c  o m*/
protected void injectFeatureLibraries(Gadget gadget, Node headTag, Node firstHeadChild) throws GadgetException {
    // TODO: If there isn't any js in the document, we can skip this. Unfortunately, that means
    // both script tags (easy to detect) and event handlers (much more complex).
    GadgetContext context = gadget.getContext();

    // Set of extern libraries requested by the container
    Set<String> externForcedLibs = defaultExternLibs;

    // gather the libraries we'll need to generate the extern libs
    String externParam = context.getParameter("libs");
    if (StringUtils.isNotBlank(externParam)) {
        externForcedLibs = Sets.newTreeSet(Arrays.asList(StringUtils.split(externParam, ':')));
    }

    if (!externForcedLibs.isEmpty()) {
        String jsUrl = jsUriManager.makeExternJsUri(gadget, externForcedLibs).toString();
        Element libsTag = headTag.getOwnerDocument().createElement("script");
        libsTag.setAttribute("src", jsUrl);
        headTag.insertBefore(libsTag, firstHeadChild);
    }

    List<String> unsupported = Lists.newLinkedList();

    List<FeatureResource> externForcedResources = featureRegistry.getFeatureResources(context, externForcedLibs,
            unsupported);
    if (!unsupported.isEmpty()) {
        LOG.info("Unknown feature(s) in extern &libs=: " + unsupported.toString());
        unsupported.clear();
    }

    // Get all resources requested by the gadget's requires/optional features.
    Map<String, Feature> featureMap = gadget.getSpec().getModulePrefs().getFeatures();
    List<String> gadgetFeatureKeys = Lists.newArrayList(gadget.getDirectFeatureDeps());
    List<FeatureResource> gadgetResources = featureRegistry.getFeatureResources(context, gadgetFeatureKeys,
            unsupported);
    if (!unsupported.isEmpty()) {
        List<String> requiredUnsupported = Lists.newLinkedList();
        for (String notThere : unsupported) {
            if (!featureMap.containsKey(notThere) || featureMap.get(notThere).getRequired()) {
                // if !containsKey, the lib was forced with Gadget.addFeature(...) so implicitly req'd.
                requiredUnsupported.add(notThere);
            }
        }
        if (!requiredUnsupported.isEmpty()) {
            throw new UnsupportedFeatureException(requiredUnsupported.toString());
        }
    }

    // Inline or externalize the gadgetFeatureKeys
    List<FeatureResource> inlineResources = Lists.newArrayList();
    List<String> allRequested = Lists.newArrayList(gadgetFeatureKeys);

    if (externalizeFeatures) {
        Set<String> externGadgetLibs = Sets.newTreeSet(featureRegistry.getFeatures(gadgetFeatureKeys));
        externGadgetLibs.removeAll(externForcedLibs);

        if (!externGadgetLibs.isEmpty()) {
            String jsUrl = jsUriManager.makeExternJsUri(gadget, externGadgetLibs).toString();
            Element libsTag = headTag.getOwnerDocument().createElement("script");
            libsTag.setAttribute("src", jsUrl);
            headTag.insertBefore(libsTag, firstHeadChild);
        }
    } else {
        inlineResources.addAll(gadgetResources);
    }

    // Calculate inlineResources as all resources that are needed by the gadget to
    // render, minus all those included through externResources.
    // TODO: profile and if needed, optimize this a bit.
    if (!externForcedLibs.isEmpty()) {
        allRequested.addAll(externForcedLibs);
        inlineResources.removeAll(externForcedResources);
    }

    // Precalculate the maximum length in order to avoid excessive garbage generation.
    int size = 0;
    for (FeatureResource resource : inlineResources) {
        if (!resource.isExternal()) {
            if (context.getDebug()) {
                size += resource.getDebugContent().length();
            } else {
                size += resource.getContent().length();
            }
        }
    }

    String libraryConfig = getLibraryConfig(gadget, featureRegistry.getFeatures(allRequested));

    // Size has a small fudge factor added to it for delimiters and such.
    StringBuilder inlineJs = new StringBuilder(size + libraryConfig.length() + INLINE_JS_BUFFER);

    // Inline any libs that weren't extern. The ugly context switch between inline and external
    // Js is needed to allow both inline and external scripts declared in feature.xml.
    for (FeatureResource resource : inlineResources) {
        String theContent = context.getDebug() ? resource.getDebugContent() : resource.getContent();
        if (resource.isExternal()) {
            if (inlineJs.length() > 0) {
                Element inlineTag = headTag.getOwnerDocument().createElement("script");
                headTag.insertBefore(inlineTag, firstHeadChild);
                inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.toString()));
                inlineJs.setLength(0);
            }
            Element referenceTag = headTag.getOwnerDocument().createElement("script");
            referenceTag.setAttribute("src", theContent);
            headTag.insertBefore(referenceTag, firstHeadChild);
        } else {
            inlineJs.append(theContent).append(";\n");
        }
    }

    inlineJs.append(libraryConfig);

    if (inlineJs.length() > 0) {
        Element inlineTag = headTag.getOwnerDocument().createElement("script");
        headTag.insertBefore(inlineTag, firstHeadChild);
        inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.toString()));
    }
}

From source file:org.automagic.deps.doctor.editor.PomWriterImpl.java

private void addIndentedNode(final Node parent, Node newChild, int indent) {

    Optional<Node> insertionPoint = getInsertionPoint(parent);

    List<Node> indentedList = indent(newChild, indent);
    Collections.reverse(indentedList);

    Node point = insertionPoint.get();
    for (Node node : indentedList) {
        if (insertionPoint.isPresent()) {
            parent.insertBefore(node, point);
            point = node;/*w ww  .j a  v a 2  s.  c  om*/
        } else {
            parent.appendChild(node);
        }
    }
}

From source file:org.chiba.xml.xforms.core.Instance.java

/**
 * Inserts the specified node.//from   w w  w .  java2s  .  co m
 *
 * @param origin the path pointing to the origin node.
 * @param before the path pointing to the node before which a clone of the
 * origin node will be inserted.
 */
public void insertNode(String origin, String before) throws XFormsException {
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(this + " insert node: " + origin + " before " + before);
        getLogger().debug(
                this + " insert node: instance data before manipulation" + toString(this.instanceDocument));
    }

    // lookup manadatory origin node
    ModelItem originItem = getModelItem(origin);
    Node originNode;
    if (originItem != null) {
        originNode = (Node) originItem.getNode();
    } else {
        throw new XFormsException("origin node does not exist");
    }

    // lookup optional before node
    ModelItem beforeItem = getModelItem(before);
    Node beforeNode = null;
    String beforePath = null;
    if (beforeItem != null) {
        // get node and parent path
        beforeNode = (Node) beforeItem.getNode();
        beforePath = before;
    } else {
        // lookup following sibling of last node in 'before' nodeset
        String firstSibling = XPathUtil.getNodesetAndPredicates(before)[0] + "[last()]/following-sibling::*[1]";
        beforeItem = getModelItem(firstSibling);

        if (beforeItem != null) {
            // get node and parent path
            beforeNode = (Node) beforeItem.getNode();
            beforePath = firstSibling;
        }
    }

    // lookup manadatory parent node
    String parent;
    if (beforePath != null) {
        parent = beforePath + "/..";
    } else {
        String[] parentParts = XPathUtil.splitPathExpr(before);
        parent = XPathUtil.joinPathExpr(parentParts, 0, parentParts.length - 1);
    }

    ModelItem parentItem = getModelItem(parent);
    Node parentNode;
    if (parentItem != null) {
        parentNode = (Node) parentItem.getNode();
    } else {
        throw new XFormsException("parent node does not exist");
    }

    // insert a deep clone of 'origin' node before 'before' node. if
    // 'before' node is null, the clone will be appended to 'parent' node.
    parentNode.insertBefore(this.instanceDocument.importNode(originNode, true), beforeNode);

    // get canonical path for inserted node
    String canonicalPath = this.instanceContext.getPointer(beforeItem != null ? before : parent + "/*[last()]")
            .asPath();
    String[] canonicalParts = XPathUtil.getNodesetAndPredicates(canonicalPath);

    // dispatch internal chiba event (for instant repeat updating)
    HashMap map = new HashMap();
    map.put("nodeset", canonicalParts[0]);
    map.put("position", canonicalParts[1]);
    this.container.dispatch(this.target, ChibaEventNames.NODE_INSERTED, map);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " insert node: instance data after manipulation" + toString(this.instanceDocument));
    }
}

From source file:org.chiba.xml.xforms.Instance.java

/**
 * Inserts the specified node./*from  w w w . j a va  2 s. com*/
 *
 * @param path     the path pointing to a nodeset.
 * @param position the nodeset position.
 */
public void insertNode(String path, int position) throws XFormsException {
    String insertPath = path + "[" + position + "]";
    if (getLogger().isDebugEnabled()) {
        getLogger().debug(this + " insert node: " + insertPath);
        getLogger().debug(
                this + " insert node: instance data before manipulation" + toString(this.instanceDocument));
    }

    // [1] check insert position
    if (position < 1 || position > countNodeset(path) + 1) {
        throw new XFormsException("invalid insert path '" + insertPath + "'");
    }

    // [2] lookup required parent node
    Node parentNode = getInsertParent(path);

    // [3] lookup optional reference node
    Node refNode = getInsertReference(path, position);

    // [4] lookup required collection member
    Node finalMember = getFinalCollectionMember(path);

    // [5] clone final collection member
    Node newNode = this.instanceDocument.importNode(finalMember, true);

    // [6] insert new node at specified position
    parentNode.insertBefore(newNode, refNode);

    // [7] canonicalize insert path and dispatch chiba event
    insertPath = this.instanceContext.getPointer(insertPath).asPath();
    this.container.dispatch(this.target, EventFactory.NODE_INSERTED, insertPath);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug(
                this + " insert node: instance data after manipulation" + toString(this.instanceDocument));
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Replace one node with a list of nodes.
 * @param newNodes New nodes - added in same location as oldNode.
 * @param oldNode Old node - removed./*www.  j a va  2 s  .c  om*/
 * @param clone Clone Nodelist Nodes.
 */
public static void replaceNode(NodeList newNodes, Node oldNode, boolean clone) {
    AssertArgument.isNotNull(newNodes, "newNodes");
    AssertArgument.isNotNull(oldNode, "oldNode");

    Node parentNode = oldNode.getParentNode();

    if (parentNode == null) {
        logger.debug("Cannot replace [" + oldNode + "] with a NodeList. [" + oldNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        if (!(parentNode instanceof Document)) {
            parentNode.removeChild(oldNode);
        }
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            logger.debug(
                    "Request to replace the Document root node with a 1+ in length NodeList.  Replacing root node with the first element node from the NodeList.");
            parentNode.removeChild(oldNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            logger.debug(
                    "Cannot replace document root element with a NodeList that doesn't contain an element node.");
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            if (clone) {
                parentNode.insertBefore(((Node) nodeList.get(i)).cloneNode(true), oldNode);
            } else {
                parentNode.insertBefore((Node) nodeList.get(i), oldNode);
            }
        }
        parentNode.removeChild(oldNode);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied node before the supplied reference node (refNode).
 * @param newNode Node to be inserted./*from   www  .  j  ava  2s  . co m*/
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.
 */
public static void insertBefore(Node newNode, Node refNode) {
    AssertArgument.isNotNull(newNode, "newNode");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug(
                "Cannot insert [" + newNode + "] before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    if (parentNode instanceof Document && newNode.getNodeType() == Node.ELEMENT_NODE) {
        logger.debug(
                "Request to insert an element before the Document root node.  This is not allowed.  Replacing the Document root with the new Node.");
        parentNode.removeChild(refNode);
        parentNode.appendChild(newNode);
    } else {
        parentNode.insertBefore(newNode, refNode);
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Insert the supplied nodes before the supplied reference node (refNode).
 * @param newNodes Nodes to be inserted.
 * @param refNode Reference node before which the supplied nodes should
 * be inserted.//from ww  w  . ja  v  a2 s  . com
 */
public static void insertBefore(NodeList newNodes, Node refNode) {
    AssertArgument.isNotNull(newNodes, "newNodes");
    AssertArgument.isNotNull(refNode, "refNode");

    Node parentNode = refNode.getParentNode();

    if (parentNode == null) {
        logger.debug("Cannot insert a NodeList before [" + refNode + "]. [" + refNode + "] has no parent.");
        return;
    }

    int nodeCount = newNodes.getLength();
    List nodeList = DomUtils.copyNodeList(newNodes);

    if (nodeCount == 0) {
        return;
    }

    if (parentNode instanceof Document) {
        List elements = DomUtils.getElements(newNodes, "*", null);

        if (!elements.isEmpty()) {
            logger.debug(
                    "Request to insert a NodeList before the Document root node.  Will replace the root element with the 1st element node from the NodeList.");
            parentNode.removeChild(refNode);
            parentNode.appendChild((Node) elements.get(0));
        } else {
            logger.debug(
                    "Cannot insert beforen the document root element from a NodeList that doesn't contain an element node.");
        }

        for (int i = 0; i < nodeCount; i++) {
            Node node = (Node) nodeList.get(i);
            if (node.getNodeType() != Node.ELEMENT_NODE) {
                System.out.println("****" + node);
                parentNode.insertBefore(node, refNode);
            }
        }
    } else {
        for (int i = 0; i < nodeCount; i++) {
            parentNode.insertBefore((Node) nodeList.get(i), refNode);
        }
    }
}