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.infoscoop.service.SiteAggregationMenuService.java

public synchronized void updateMenuItem(String menuId, String title, String href, String display, String type,
        String serviceURL, String serviceAuthType, Map props, String alert, String menuType, Collection auths,
        Collection<String> menuTreeAdmins, Boolean linkDisabled, String directoryTitle, String sitetopId,
        boolean multi) throws Exception {

    href = StringUtil.getTruncatedString(href, 1024, "UTF-8");

    if (log.isInfoEnabled()) {
        log.info("UpdateMenuItem: menuId=" + menuId + ", title=" + title + ", " + title + ", href=" + href
                + ", display=" + display + ", alert" + alert + ", properties=" + props);
    }/*from   ww  w .  ja v  a 2  s .c  o  m*/
    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp entity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, sitetopId);
    Node node = getTargetElement(entity, menuId);

    // Error
    if (node == null)
        throw new Exception("element not found [//site],[//site-top]");

    Document document = node.getOwnerDocument();

    // Create element to be updated
    Element element;
    element = (Element) node;
    element.setAttribute("title", title);
    element.setAttribute("href", href);
    element.setAttribute("display", display);
    element.setAttribute("link_disabled", linkDisabled.toString());
    if (serviceURL != null)
        element.setAttribute("serviceURL", serviceURL);
    if (serviceAuthType != null)
        element.setAttribute("serviceAuthType", serviceAuthType);
    if (alert != null && !"".equals(alert))
        element.setAttribute("alert", alert);

    element.setAttribute("multi", String.valueOf(multi));

    element.setAttribute("type", type);

    if (directoryTitle != null && !"".equals(directoryTitle)) {
        element.setAttribute("directory_title", directoryTitle);
    } else if (element.hasAttribute("directory_title")) {
        element.removeAttribute("directory_title");
    }

    element.insertBefore(recreatePropertiesNode(document, element, props), element.getFirstChild());

    Element oldAuths = getFirstChildElementByName(element, "auths");
    if (oldAuths != null) {
        element.removeChild(oldAuths);
    }
    if (auths != null) {
        element.insertBefore(MenuAuthorization.createAuthsElement(document, auths),
                getFirstChildElementByName(element, "site"));
    }

    NodeList oldAdmins = element.getElementsByTagName("menuTreeAdmins");
    if (oldAdmins != null) {
        while (oldAdmins.getLength() != 0) {
            oldAdmins.item(0).getParentNode().removeChild(oldAdmins.item(0));
        }
    }
    if (menuTreeAdmins != null) {
        element.insertBefore(createAdminsElement(document, menuTreeAdmins),
                getFirstChildElementByName(element, "site"));
    }

    // Update
    entity.setElement(document.getDocumentElement());
    this.siteAggregationMenuTempDAO.update(entity);
}

From source file:org.infoscoop.service.SiteAggregationMenuService.java

/**
 * @param menuId//from   w ww.  ja v  a  2s  . c om
 * @param siblingId
 * @throws Exception 
 */
public synchronized void replaceOrder(String menuType, String menuId, String parentId, String siblingId,
        String fromSitetopId, String toSitetopId) throws Exception {
    if (log.isInfoEnabled()) {
        log.info("MoveMenuItem: menuId=" + menuId + ", parentId=" + parentId + ", siblingId=" + siblingId
                + ", menuType=" + menuType + ", fromSitetopId=" + fromSitetopId + ", toSitetopId="
                + toSitetopId);
    }

    boolean isSameTree = fromSitetopId.equals(toSitetopId);

    // Obtain data and transfer the result to Document.
    Siteaggregationmenu_temp fromEntity = this.siteAggregationMenuTempDAO.selectBySitetopId(menuType,
            fromSitetopId);
    Siteaggregationmenu_temp toEntity = (isSameTree) ? fromEntity
            : this.siteAggregationMenuTempDAO.selectBySitetopId(menuType, toSitetopId);

    Element menuNode = getTargetElement(fromEntity, menuId);

    // Error
    if (menuNode == null)
        throw new Exception("menuNode not found [//site],[//site-top]");

    Element fromMenuEl = menuNode.getOwnerDocument().getDocumentElement();
    Element toMenuEl = (isSameTree) ? fromMenuEl : toEntity.getElement();
    Document document = toMenuEl.getOwnerDocument();

    // Search for node matches parentId from <site-top> or <site>
    Element parentNode = (Element) AdminServiceUtil.getNodeById(document, "//site", parentId);
    if (parentNode == null)
        parentNode = (Element) AdminServiceUtil.getNodeById(document, "//site-top", parentId);

    // Search for node matches siblingId from parentNode
    Element siblingNode = (Element) AdminServiceUtil.getNodeById(document, "//site", siblingId);

    Element moveMenuNodeCopy = (Element) document.importNode(menuNode, true);
    if (siblingNode == null) {
        parentNode.appendChild(moveMenuNodeCopy);
    } else {
        parentNode.insertBefore(moveMenuNodeCopy, siblingNode);
    }

    // Delete the node moving from.
    AdminServiceUtil.removeSelf(menuNode);

    // Update the node moving to.
    toEntity.setElement(toMenuEl);
    this.siteAggregationMenuTempDAO.update(toEntity);

    // Update source entity if it is moved between tree.
    if (!isSameTree) {
        fromEntity.setElement(fromMenuEl);
        this.siteAggregationMenuTempDAO.update(fromEntity);
    }
}

From source file:org.infoscoop.service.WidgetConfService.java

/**
 * @param doc//from   w  w w  . ja v a2  s. co  m
 * @param widgetConfNode
 * @param updatePrefList
 * @throws JSONException
 */
public static void updateWidgetPrefNode(Document doc, Element widgetConfNode, JSONObject updatePrefList)
        throws JSONException {

    NodeList prefList = widgetConfNode.getElementsByTagName("WidgetPref");

    Iterator keys = updatePrefList.keys();
    while (keys.hasNext()) {
        String id = (String) keys.next();
        JSONObject prefJson = updatePrefList.getJSONObject(id);
        if (!prefJson.has("name"))
            continue;

        String name = prefJson.getString("name");

        String datatype = "";
        if (prefJson.has("datatype"))
            datatype = prefJson.getString("datatype");

        String value = prefJson.getString("value");

        int prefLength = prefList.getLength();
        boolean update = false;
        for (int i = 0; i < prefLength; i++) {
            Element pref = (Element) prefList.item(i);
            if (!name.equals(pref.getAttribute("name")))
                continue;

            if ("xml".equals(datatype) || "json".equals(datatype)) {
                while (pref.getFirstChild() != null)
                    pref.removeChild(pref.getFirstChild());

                pref.appendChild(doc.createTextNode(value));
            } else {
                pref.setAttribute("value", value);
            }

            update = true;
        }

        // is this code require ?
        if (!update) {
            Element newPref = doc.createElement("WidgetPref");
            newPref.setAttribute("name", name);

            if ("xml".equals(datatype) || "json".equals(datatype)) {
                newPref.appendChild(doc.createTextNode(value));
            } else {
                newPref.setAttribute("value", value);
            }
            int lastPrefIndex = prefList.getLength() - 1;
            Element lastPref = (Element) prefList.item(lastPrefIndex);
            Element nextPrefNode = (Element) lastPref.getNextSibling();
            if (nextPrefNode != null) {
                widgetConfNode.insertBefore(newPref, nextPrefNode);
            } else {
                widgetConfNode.appendChild(newPref);
            }
        }
    }
}

From source file:org.infoscoop.service.WidgetConfService.java

/**
 * @param doc/*ww  w.  j av a  2  s.c  o m*/
 * @param widgetConfNode
 * @param updatePrefList
 * @throws JSONException
 */
private void updateUserPrefNode(Document doc, Element widgetConfNode, JSONObject updatePrefList)
        throws JSONException {

    NodeList prefList = widgetConfNode.getElementsByTagName("UserPref");

    Iterator keys = updatePrefList.keys();
    while (keys.hasNext()) {
        String id = (String) keys.next();
        JSONObject prefJson = updatePrefList.getJSONObject(id);

        if (!prefJson.has("name"))
            continue;

        String name = prefJson.getString("name");

        if (!prefJson.has("default_value"))
            continue;
        String value = prefJson.getString("default_value");

        String datatype = null;
        if (prefJson.has("datatype"))
            datatype = prefJson.getString("datatype");

        int prefLength = prefList.getLength();
        boolean update = false;
        for (int i = 0; i < prefLength; i++) {
            Element pref = (Element) prefList.item(i);
            if (!name.equals(pref.getAttribute("name")))
                continue;

            if ("xml".equals(datatype) || "json".equals(datatype)) {
                while (pref.getFirstChild() != null)
                    pref.removeChild(pref.getFirstChild());

                pref.appendChild(doc.createTextNode(value));
            } else {
                pref.setAttribute("default_value", value);
            }

            update = true;
        }

        // is this code require ?
        // and this code is obsolete.  what is "inputType" attribute ?
        if (!update) {
            Element newPref = doc.createElement("UserPref");
            newPref.setAttribute("name", name);

            if (("xml".equals(datatype) || "json".equals(datatype))) {
                newPref.appendChild(doc.createTextNode(value));
            } else {
                newPref.setAttribute("default_value", value);
            }

            String inputType = prefJson.getString("inputType");
            if (inputType != null) {
                newPref.setAttribute("inputType", inputType);
            }
            String displayName = prefJson.getString("display_name");
            if (prefJson.has("display_name")) {
                newPref.setAttribute("display_name", displayName);
            }
            if (prefJson.has("EnumValue")) {
                JSONArray options = prefJson.getJSONArray("EnumValue");
                for (int j = 0; j < options.length(); j++) {
                    JSONObject option = options.getJSONObject(j);
                    Element optionNode = doc.createElement("EnumValue");
                    optionNode.setAttribute("display_value", option.getString("display_value"));
                    optionNode.setAttribute("value", option.getString("value"));
                    newPref.appendChild(optionNode);
                }
            }

            int lastPrefIndex = prefList.getLength() - 1;
            Element lastPref = (Element) prefList.item(lastPrefIndex);
            Element nextPrefNode = (Element) lastPref.getNextSibling();
            if (nextPrefNode != null) {
                widgetConfNode.insertBefore(newPref, nextPrefNode);
            } else {
                widgetConfNode.appendChild(newPref);
            }
        }
    }
}

From source file:org.jasig.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./* w ww .j  a  v a 2  s .  c o  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 iter = order.iterator(); iter.hasNext();) {
        NodeInfo ni = (NodeInfo) iter.next();

        if (ni.positionDirective != 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.positionDirective != nodeToMatch)
                result.changedPLF = 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.positionDirective, 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.jasig.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  ww  w. j  a va 2 s. c  om*/
 */
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(((NodeInfo) order.get(i)).node, insertPoint);

    compViewParent.removeChild(insertPoint);
}

From source file:org.kuali.rice.edl.impl.components.SelectControlEDLComponent.java

protected void includeValuesGroup(Element valuesGroupElem) {
    Element valuesGroupParent = (Element) valuesGroupElem.getParentNode();
    NodeList valuesGroupChildren = valuesGroupElem.getChildNodes();

    for (int index = 0; index < valuesGroupChildren.getLength(); index++) {
        Node item = valuesGroupChildren.item(index);
        if (Node.ELEMENT_NODE == item.getNodeType() && item.getNodeName().equals("values")) {
            valuesGroupParent.insertBefore(item, valuesGroupElem);
        }/*from   w w  w  .  j a  v  a 2s . c  o  m*/
    }
    valuesGroupParent.removeChild(valuesGroupElem);
}

From source file:org.kuali.rice.krad.datadictionary.parse.CustomSchemaParser.java

/**
 * Parses a bean of the spring namespace.
 *
 * @param tag - The Element to be parsed.
 * @return The parsed bean.//from w  w w . j av  a 2s. c  o m
 */
protected Object parseSpringBean(Element tag, ParserContext parserContext) {
    if (tag.getLocalName().compareTo("ref") == 0) {
        // Create the referenced bean by creating a new bean and setting its parent to the referenced bean
        // then replace grand child with it
        Element temp = tag.getOwnerDocument().createElement("bean");
        temp.setAttribute("parent", tag.getAttribute("bean"));
        tag = temp;
        return new RuntimeBeanReference(tag.getAttribute("parent"));
    }

    //peel off p: properties an make them actual property nodes - p-namespace does not work properly (unknown cause)
    Document document = tag.getOwnerDocument();
    NamedNodeMap attributes = tag.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);
        String name = attribute.getNodeName();
        if (name.startsWith("p:")) {
            Element property = document.createElement("property");
            property.setAttribute("name", StringUtils.removeStart(name, "p:"));
            property.setAttribute("value", attribute.getTextContent());

            if (tag.getFirstChild() != null) {
                tag.insertBefore(property, tag.getFirstChild());
            } else {
                tag.appendChild(property);
            }
        }
    }

    // Create the bean definition for the grandchild and return it.
    BeanDefinitionParserDelegate delegate = parserContext.getDelegate();
    BeanDefinitionHolder bean = delegate.parseBeanDefinitionElement(tag);

    // Creates a custom name for the new bean.
    String name = bean.getBeanDefinition().getParentName() + "$Customchild" + beanNumber;
    if (tag.getAttribute("id") != null && !StringUtils.isEmpty(tag.getAttribute("id"))) {
        name = tag.getAttribute("id");
    } else {
        beanNumber++;
    }

    return new BeanDefinitionHolder(bean.getBeanDefinition(), name);
}

From source file:org.ojbc.util.xml.XmlUtils.java

/**
  * Create a new element with the specified namespace and name, insert it under the specified parent but before the specified sibling, and return it
  * //from  w  w  w.j  a  va 2s .  c  om
  * @param parent
  *            the parent
  * @param sibling
  *            the parent's current child, in front of which the new element is to be inserted
  * @param ns
  *            the namespace URI of the new element
  * @param elementName
  *            the name of the new element
  * @return the new element
  */
public static final Element insertElementBefore(Element parent, Element sibling, String ns,
        String elementName) {
    Document doc = parent.getOwnerDocument();
    Element ret = doc.createElementNS(ns, elementName);
    ret.setPrefix(OJBC_NAMESPACE_CONTEXT.getPrefix(ns));
    parent.insertBefore(ret, sibling);
    return ret;
}

From source file:org.openestate.io.immobiliare_it.ImmobiliareItDocument.java

@Override
public void setDocumentVersion(ImmobiliareItVersion version) {
    try {/*from  w  ww. j a  va 2 s.  c  o  m*/
        Document doc = this.getDocument();

        Element node = (Element) XmlUtils.newXPath("/io:feed/io:version", doc).selectSingleNode(doc);
        if (node == null) {
            Element parentNode = (Element) XmlUtils.newXPath("/io:feed", doc).selectSingleNode(doc);
            if (parentNode == null) {
                LOGGER.warn("Can't find a <feed> element in the document!");
                return;
            }
            node = doc.createElement("version");
            parentNode.insertBefore(node, parentNode.getFirstChild());
        }

        node.setTextContent(version.toReadableVersion());
    } catch (JaxenException ex) {
        LOGGER.error("Can't evaluate XPath expression!");
        LOGGER.error("> " + ex.getLocalizedMessage(), ex);
    }
}