Example usage for org.w3c.dom Element insertBefore

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

Introduction

In this page you can find the example usage for org.w3c.dom Element 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.xml.security.utils.XMLUtils.java

public static void addReturnBeforeChild(Element e, Node child) {
    if (!ignoreLineBreaks) {
        Document doc = e.getOwnerDocument();
        e.insertBefore(doc.createTextNode("\n"), child);
    }//from w  w w  . j av  a  2  s.co  m
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription node, String parentId,
        String nextSiblingId) throws PortalException {
    boolean isChannel = false;
    IUserLayoutNodeDescription parent = this.getNode(parentId);
    if (canAddNode(node, parent, nextSiblingId)) {
        // assign new Id
        try {//from w  ww .  j a v a2 s.  com
            if (node instanceof IUserLayoutChannelDescription) {
                isChannel = true;
                node.setId(this.distributedLayoutStore.generateNewChannelSubscribeId(owner));
            } else {
                node.setId(this.distributedLayoutStore.generateNewFolderId(owner));
            }
        } catch (Exception e) {
            throw new PortalException("Exception encountered while "
                    + "generating new user layout node Id for  for " + owner.getAttribute(IPerson.USERNAME), e);
        }

        Document uld = getUserLayoutDOM();
        Element childElement = node.getXML(uld);
        Element parentElement = uld.getElementById(parentId);
        if (nextSiblingId == null) {
            parentElement.appendChild(childElement);
        } else {
            Node nextSibling = uld.getElementById(nextSiblingId);
            parentElement.insertBefore(childElement, nextSibling);
        }
        // register element id
        childElement.setIdAttribute(Constants.ATT_ID, true);
        childElement.setAttribute(Constants.ATT_ID, node.getId());
        this.updateCacheKey();

        // push into the user's real layout that gets persisted.
        HandlerUtils.createPlfNodeAndPath(childElement, isChannel, owner);

        // fire event
        final int layoutId = this.getLayoutId();
        if (isChannel) {
            this.channelsAdded = true;
            final String fname = ((IUserLayoutChannelDescription) node).getFunctionalName();
            this.portalEventFactory.publishPortletAddedToLayoutPortalEvent(this, this.owner, layoutId,
                    parent.getId(), fname);
        } else {
            this.portalEventFactory.publishFolderAddedToLayoutPortalEvent(this, this.owner, layoutId,
                    node.getId());
        }

        return node;
    }
    return null;
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public boolean moveNode(String nodeId, String parentId, String nextSiblingId) throws PortalException {
    IUserLayoutNodeDescription parent = this.getNode(parentId);
    IUserLayoutNodeDescription node = this.getNode(nodeId);
    String oldParentNodeId = getParentId(nodeId);
    if (canMoveNode(node, parent, nextSiblingId)) {
        // must be a folder
        Document uld = this.getUserLayoutDOM();
        Element childElement = uld.getElementById(nodeId);
        Element parentElement = uld.getElementById(parentId);
        if (nextSiblingId == null) {
            parentElement.appendChild(childElement);
        } else {// w w w.  j  a v  a 2 s  .  c  o  m
            Node nextSibling = uld.getElementById(nextSiblingId);
            parentElement.insertBefore(childElement, nextSibling);
        }
        this.updateCacheKey();

        // propagate the change into the PLF
        Element oldParent = uld.getElementById(oldParentNodeId);
        TabColumnPrefsHandler.moveElement(childElement, oldParent, owner);
        // fire event
        final int layoutId = this.getLayoutId();
        if (node instanceof IUserLayoutChannelDescription) {
            this.channelsAdded = true;
            final String fname = ((IUserLayoutChannelDescription) node).getFunctionalName();
            this.portalEventFactory.publishPortletMovedInLayoutPortalEvent(this, this.owner, layoutId,
                    oldParentNodeId, parent.getId(), fname);
        } else {
            this.portalEventFactory.publishFolderMovedInLayoutPortalEvent(this, this.owner, layoutId,
                    oldParentNodeId, parent.getId());
        }
        return true;
    }
    return false;
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method trims down the position set to the position directives on
   the node info elements still having a position directive. Any directives
   that violated restrictions were removed from the node info objects so
   the position set should be made to match the order of those still
   having one./*from   w  ww .j av  a2 s .co  m*/
 */
static void adjustPositionSet(List<NodeInfo> order, Element positionSet, IntegrationResult result) {
    Node nodeToMatch = positionSet.getFirstChild();
    Element nodeToInsertBefore = positionSet.getOwnerDocument().createElement("INSERT_POINT");
    positionSet.insertBefore(nodeToInsertBefore, nodeToMatch);

    for (Iterator<NodeInfo> iter = order.iterator(); iter.hasNext();) {
        NodeInfo ni = iter.next();

        if (ni.getPositionDirective() != null) {
            // found one check it against the current one in the position
            // set to see if it is different. If so then indicate that
            // something (the position set) has changed in the plf
            if (ni.getPositionDirective() != nodeToMatch)
                result.setChangedPLF(true);
            ;

            // now bump the insertion point forward prior to
            // moving on to the next position node to be evaluated
            if (nodeToMatch != null)
                nodeToMatch = nodeToMatch.getNextSibling();

            // now insert it prior to insertion point
            positionSet.insertBefore(ni.getPositionDirective(), nodeToInsertBefore);
        }
    }

    // now for any left over after the insert point remove them.

    while (nodeToInsertBefore.getNextSibling() != null)
        positionSet.removeChild(nodeToInsertBefore.getNextSibling());

    // now remove the insertion point
    positionSet.removeChild(nodeToInsertBefore);
}

From source file:org.apereo.portal.layout.dlm.PositionManager.java

/**
   This method applies the ordering specified in the passed in order list
   to the child nodes of the compViewParent. Nodes specified in the list
   but located elsewhere are pulled in.//from w  w w . j  av  a  2  s  . c o m
 */
static void applyToNodes(List<NodeInfo> order, Element compViewParent) {
    // first set up a bogus node to assist with inserting
    Node insertPoint = compViewParent.getOwnerDocument().createElement("bogus");
    Node first = compViewParent.getFirstChild();

    if (first != null)
        compViewParent.insertBefore(insertPoint, first);
    else
        compViewParent.appendChild(insertPoint);

    // now pass through the order list inserting the nodes as you go
    for (int i = 0; i < order.size(); i++)
        compViewParent.insertBefore(order.get(i).getNode(), insertPoint);

    compViewParent.removeChild(insertPoint);
}

From source file:org.dita.dost.module.BranchFilterModule.java

private void filterBranches(final Element elem, final List<FilterUtils> filters, final QName[][] props) {
    final List<FilterUtils> fs = combineFilterUtils(elem, filters);

    boolean exclude = false;
    for (final FilterUtils f : fs) {
        exclude = f.needExclude(elem, props);
        if (exclude) {
            break;
        }/*from  w  ww  . j  a  v  a  2s  . com*/
    }

    if (exclude) {
        elem.getParentNode().removeChild(elem);
    } else {
        final List<Element> childElements = getChildElements(elem);
        final Set<Flag> flags = fs.stream().flatMap(f -> f.getFlags(elem, props).stream())
                .map(f -> f.adjustPath(currentFile, job)).collect(Collectors.toSet());
        for (Flag flag : flags) {
            final Element startElement = (Element) elem.getOwnerDocument().importNode(flag.getStartFlag(),
                    true);
            final Node firstChild = elem.getFirstChild();
            if (firstChild != null) {
                elem.insertBefore(startElement, firstChild);
            } else {
                elem.appendChild(startElement);
            }
            final Element endElement = (Element) elem.getOwnerDocument().importNode(flag.getEndFlag(), true);
            elem.appendChild(endElement);
        }
        for (final Element child : childElements) {
            filterBranches(child, fs, props);
        }
    }
}

From source file:org.eclipse.skalli.view.internal.servlet.StaticContentServlet.java

/**
 * Resolves all &lt;include&gt; in a given schema and writes the
 * result to the given output stream. Includes that can't be resolved
 * are removed from the schema.//  w  w w  .  ja  v a2  s  . c  o  m
 * @param in  the input stream providing the schema to resolve.
 * @param out  the output stream to write the result to.
 * @throws IOException  if an i/o error occured.
 * @throws SAXException  if parsing of the schema failed.
 * @throws ParserConfigurationException  indicates a serious parser configuration error.
 * @throws TransformerException  if transforming the schema DOM to a character stream failed.
 * @throws TransformerConfigurationException  indicates a serious transformer configuration error.
 */
private void resolveIncludes(InputStream in, OutputStream out) throws IOException, SAXException,
        ParserConfigurationException, TransformerConfigurationException, TransformerException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document schemaDOM = dbf.newDocumentBuilder().parse(new InputSource(in));
    Element schemaRoot = schemaDOM.getDocumentElement();

    // iterate all <include> tags and resolve them if possible
    NodeList includes = schemaDOM.getElementsByTagName("xsd:include");
    while (includes.getLength() > 0) {
        for (int i = 0; i < includes.getLength(); ++i) {
            Node includeNode = includes.item(i);
            Node includeParent = includeNode.getParentNode();
            Node schemaLocation = includeNode.getAttributes().getNamedItem("schemaLocation");
            if (schemaLocation != null) {
                // extract the pure file name from the schemaLocation and
                // try to find an XSD resource in all model extensions matching
                // the given schemaLocation attribute -> if found, replace the include tag
                // with the DOM of the include (without the root tag, of course!)
                URL includeFile = RestUtils.findSchemaResource(schemaLocation.getTextContent());
                if (includeFile != null) {
                    Document includeDOM = dbf.newDocumentBuilder()
                            .parse(new InputSource(includeFile.openStream()));
                    NodeList includeNodes = includeDOM.getDocumentElement().getChildNodes();
                    for (int j = 0; j < includeNodes.getLength(); ++j) {
                        // import and insert the tag before <include>
                        schemaRoot.insertBefore(schemaDOM.importNode(includeNodes.item(j), true), includeNode);
                    }
                }

                // in any case: remove the <include> tag
                includeParent.removeChild(includeNode);
            }
        }
        // resolve includes of includes (if any)
        includes = schemaDOM.getElementsByTagName("xsd:include");
    }

    // serialize the schema DOM to the given output stream
    Transformer xform = TransformerFactory.newInstance().newTransformer();
    xform.setOutputProperty(OutputKeys.INDENT, "yes");
    xform.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    xform.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    xform.transform(new DOMSource(schemaDOM), new StreamResult(out));
}

From source file:org.eclipse.smila.processing.bpel.MessageHelper.java

/**
 * add request id part as first child element of message.
 * /*from ww w  .  j  a va 2s.  c om*/
 * @param message
 *          a message variable
 * @param requestId
 *          request id.
 * @param varType
 *          type of variable. currently necessary to decide where to put the Id.
 */
public void addRequestId(final Element message, final String requestId, final QName varType) {
    Element idNode = createRequestIdNode(requestId, message.getOwnerDocument());
    final Element idPart = message.getOwnerDocument().createElementNS(null, BPELConstants.PART_ID);
    idPart.appendChild(idNode);
    idNode = idPart;
    if (DOMUtils.isEmptyElement(message)) {
        message.appendChild(idNode);
    } else {
        message.insertBefore(idNode, DOMUtils.getFirstChildElement(message));
    }
}

From source file:org.globus.wsrf.tools.wsdl.TypesProcessor.java

private void addSchemaDefinitions(String elementNS, Map schemaDocumentLocations, Element schema)
        throws Exception {
    Map map = (Map) schemaDocumentLocations.get(elementNS);
    if (map == null) {
        return;// www  .java 2s . c o m
    }
    Set locations = map.keySet();
    Iterator locationsIterator = locations.iterator();
    String targetNS = schema.getAttribute("targetNamespace");
    Document owner = schema.getOwnerDocument();
    String schemaPrefix = schema.getPrefix();
    if (schemaPrefix == null) {
        schemaPrefix = "";
    } else {
        schemaPrefix += ":";
    }
    this.populateImportsMap(schema);
    this.populateIncludesMap(schema);

    while (locationsIterator.hasNext()) {
        String location = (String) locationsIterator.next();
        if (!location.equals(definition.getDocumentBaseURI())) {
            location = WSDLPreprocessor.getRelativePath(definition.getDocumentBaseURI(), location);

            if (elementNS.equals(targetNS)) {
                Map includes = (Map) this.includes.get(elementNS);

                if (includes == null) {
                    includes = new HashMap();
                    this.includes.put(elementNS, includes);
                }

                if (!includes.containsKey(location)) {
                    Element include = owner.createElementNS(XSD_NS, schemaPrefix + "include");
                    include.setAttribute("schemaLocation", location);
                    schema.insertBefore(owner.createTextNode("\n"), schema.getFirstChild());
                    schema.insertBefore(include, schema.getFirstChild());
                    schema.insertBefore(owner.createTextNode("\n"), schema.getFirstChild());
                    includes.put(location, null);
                }
            } else {
                Map imports = (Map) this.imports.get(elementNS);

                if (imports == null) {
                    imports = new HashMap();
                    this.imports.put(elementNS, imports);
                }

                if (!imports.containsKey(location)) {
                    Element xsdImport = owner.createElementNS(XSD_NS, schemaPrefix + "import");
                    xsdImport.setAttribute("namespace", elementNS);
                    xsdImport.setAttribute("schemaLocation", location);
                    schema.insertBefore(owner.createTextNode("\n"), schema.getFirstChild());
                    schema.insertBefore(xsdImport, schema.getFirstChild());
                    schema.insertBefore(owner.createTextNode("\n"), schema.getFirstChild());
                    imports.put(location, null);
                }
            }
        }
    }
}

From source file:org.gvnix.web.screen.roo.addon.WebScreenOperationsImpl.java

/**
 * Updates load-scripts.tagx adding in the right position some elements:
 * <ul>/*from w  ww. j a v a2  s.  c  om*/
 * <li><code>spring:url</code> elements for JS and CSS</li>
 * <li><code>link</code> element for CSS</li>
 * <li><code>script</code> element for JS</li>
 * </ul>
 */
private void modifyLoadScriptsTagx() {
    PathResolver pathResolver = projectOperations.getPathResolver();
    String loadScriptsTagx = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            "WEB-INF/tags/util/load-scripts.tagx");

    if (!fileManager.exists(loadScriptsTagx)) {
        // load-scripts.tagx doesn't exist, so nothing to do
        return;
    }

    InputStream loadScriptsIs = fileManager.getInputStream(loadScriptsTagx);

    Document loadScriptsXml;
    try {
        loadScriptsXml = XmlUtils.getDocumentBuilder().parse(loadScriptsIs);
    } catch (Exception ex) {
        throw new IllegalStateException("Could not open load-scripts.tagx file", ex);
    }

    Element lsRoot = loadScriptsXml.getDocumentElement();

    Node nextSibiling;

    // spring:url elements
    Element testElement = XmlUtils.findFirstElement("/root/url[@var='pattern_css_url']", lsRoot);
    if (testElement == null) {
        Element urlPatternCss = new XmlElementBuilder("spring:url", loadScriptsXml)
                .addAttribute(VALUE, "/resources/styles/pattern.css").addAttribute(VAR, "pattern_css_url")
                .build();
        Element urlQlJs = new XmlElementBuilder("spring:url", loadScriptsXml)
                .addAttribute(VALUE, "/resources/scripts/quicklinks.js").addAttribute(VAR, "qljs_url").build();
        // Add i18n messages for quicklinks.js
        List<Element> qlJsI18n = new ArrayList<Element>();
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_selectrowtodelete_alert")
                .addAttribute(VAR, "msg_selectrowtodelete_alert").addAttribute("htmlEscape", "false").build());
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_selectrowtoupdate_alert")
                .addAttribute(VAR, "msg_selectrowtoupdate_alert").addAttribute("htmlEscape", "false").build());
        qlJsI18n.add(new XmlElementBuilder("spring:message", loadScriptsXml)
                .addAttribute("code", "message_updateonlyonerow_alert")
                .addAttribute(VAR, "msg_updateonlyonerow_alert").addAttribute("htmlEscape", "false").build());
        StringBuilder qlJsI18nScriptText = new StringBuilder("<!--\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_SELECT_ROW_TO_DELETE=\"${msg_selectrowtodelete_alert}\";\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_SELECT_ROW_TO_UPDATE=\"${msg_selectrowtoupdate_alert}\";\n");
        qlJsI18nScriptText.append("var GVNIX_MSG_UPDATE_ONLY_ONE_ROW=\"${msg_updateonlyonerow_alert}\";\n");
        qlJsI18nScriptText.append("-->\n");
        Element qlJsI18nScript = new XmlElementBuilder("script", loadScriptsXml)
                .setText(qlJsI18nScriptText.toString()).build();
        List<Element> springUrlElements = XmlUtils.findElements("/root/url", lsRoot);
        // Element lastSpringUrl = null;
        if (!springUrlElements.isEmpty()) {
            Element lastSpringUrl = springUrlElements.get(springUrlElements.size() - 1);
            if (lastSpringUrl != null) {
                nextSibiling = lastSpringUrl.getNextSibling().getNextSibling();
                lsRoot.insertBefore(urlPatternCss, nextSibiling);
                lsRoot.insertBefore(urlQlJs, nextSibiling);
                lsRoot.insertBefore(qlJsI18nScript, nextSibiling);
                for (Element item : qlJsI18n) {
                    lsRoot.insertBefore(item, qlJsI18nScript);
                }
            }
        } else {
            // Add at the end of the document
            lsRoot.appendChild(urlPatternCss);
            lsRoot.appendChild(urlQlJs);
            for (Element item : qlJsI18n) {
                lsRoot.appendChild(item);
            }
            lsRoot.appendChild(qlJsI18nScript);
        }
    }

    // pattern.css stylesheet element
    testElement = XmlUtils.findFirstElement("/root/link[@href='${pattern_css_url}']", lsRoot);
    if (testElement == null) {
        Element linkPatternCss = new XmlElementBuilder("link", loadScriptsXml).addAttribute("rel", "stylesheet")
                .addAttribute("type", "text/css").addAttribute("media", "screen")
                .addAttribute("href", "${pattern_css_url}").build();
        linkPatternCss.appendChild(loadScriptsXml.createComment(" required for FF3 and Opera "));
        Node linkTrundraCssNode = XmlUtils.findFirstElement("/root/link[@href='${tundra_url}']", lsRoot);
        if (linkTrundraCssNode != null) {
            nextSibiling = linkTrundraCssNode.getNextSibling().getNextSibling();
            lsRoot.insertBefore(linkPatternCss, nextSibiling);
        } else {
            // Add ass last link element
            // Element lastLink = null;
            List<Element> linkElements = XmlUtils.findElements("/root/link", lsRoot);
            if (!linkElements.isEmpty()) {
                Element lastLink = linkElements.get(linkElements.size() - 1);
                if (lastLink != null) {
                    nextSibiling = lastLink.getNextSibling().getNextSibling();
                    lsRoot.insertBefore(linkPatternCss, nextSibiling);
                }
            } else {
                // Add at the end of document
                lsRoot.appendChild(linkPatternCss);
            }
        }
    }

    // quicklinks.js script element
    testElement = XmlUtils.findFirstElement("/root/script[@src='${qljs_url}']", lsRoot);
    if (testElement == null) {
        Element scriptQlJs = new XmlElementBuilder("script", loadScriptsXml).addAttribute("src", "${qljs_url}")
                .addAttribute("type", "text/javascript").build();
        scriptQlJs.appendChild(loadScriptsXml.createComment(" required for FF3 and Opera "));
        List<Element> scrtiptElements = XmlUtils.findElements("/root/script", lsRoot);
        // Element lastScript = null;
        if (!scrtiptElements.isEmpty()) {
            Element lastScript = scrtiptElements.get(scrtiptElements.size() - 1);
            if (lastScript != null) {
                nextSibiling = lastScript.getNextSibling().getNextSibling();
                lsRoot.insertBefore(scriptQlJs, nextSibiling);
            }
        } else {
            // Add at the end of document
            lsRoot.appendChild(scriptQlJs);
        }
    }

    writeToDiskIfNecessary(loadScriptsTagx, loadScriptsXml.getDocumentElement());

}