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:org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController.java

public String copyAttribute(String remoteSchemaValue, String localSchemaValue,
        String contentTypeAttributeName) {
    String newSchemaValue = localSchemaValue;

    try {//from  www  .ja v a  2 s .  com
        Document remoteDocument = createDocumentFromDefinition(remoteSchemaValue);
        Document localDocument = createDocumentFromDefinition(localSchemaValue);

        String attributeXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all/xs:element[@name='"
                + contentTypeAttributeName + "']";
        Node attributeNode = org.apache.xpath.XPathAPI.selectSingleNode(remoteDocument.getDocumentElement(),
                attributeXPath);

        String attributesXPath = "/xs:schema/xs:complexType/xs:all/xs:element/xs:complexType/xs:all";
        Node attributesNode = org.apache.xpath.XPathAPI.selectSingleNode(localDocument.getDocumentElement(),
                attributesXPath);
        logger.info("attributesNode:" + attributesNode);
        if (attributesNode != null && localDocument != null && attributeNode != null) {
            Node node = localDocument.importNode(attributeNode, true);

            attributesNode.appendChild(node);

            StringBuffer sb = new StringBuffer();
            org.infoglue.cms.util.XMLHelper.serializeDom(localDocument.getDocumentElement(), sb);
            newSchemaValue = sb.toString();
        } else {
            logger.error("Problem:" + attributesNode + " - " + localDocument + " - " + attributeNode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return newSchemaValue;
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController.java

public String copyCategory(String remoteSchemaValue, String localSchemaValue, String categoryName) {
    String newSchemaValue = localSchemaValue;

    try {/*from ww w.j  av a  2s .  co  m*/
        Document remoteDocument = createDocumentFromDefinition(remoteSchemaValue);
        Document localDocument = createDocumentFromDefinition(localSchemaValue);

        String attributeXPath = "/xs:schema/xs:simpleType[@name='categoryKeys']/xs:restriction/xs:enumeration[@value='"
                + categoryName + "']";
        Node attributeNode = org.apache.xpath.XPathAPI.selectSingleNode(remoteDocument.getDocumentElement(),
                attributeXPath);

        String attributesXPath = "/xs:schema/xs:simpleType[@name='categoryKeys']/xs:restriction";
        Node attributesNode = org.apache.xpath.XPathAPI.selectSingleNode(localDocument.getDocumentElement(),
                attributesXPath);
        if (attributesNode == null) {
            attributesNode = ContentTypeDefinitionController.getController()
                    .createNewEnumerationKey(localDocument, ContentTypeDefinitionController.CATEGORY_KEYS);
        }

        if (attributesNode != null && localDocument != null && attributeNode != null) {
            Node node = localDocument.importNode(attributeNode, true);
            attributesNode.appendChild(node);

            StringBuffer sb = new StringBuffer();
            org.infoglue.cms.util.XMLHelper.serializeDom(localDocument.getDocumentElement(), sb);
            newSchemaValue = sb.toString();
        } else {
            logger.error("Problem:" + attributesNode + " - " + localDocument + " - " + attributeNode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return newSchemaValue;
}

From source file:org.infoglue.cms.controllers.kernel.impl.simple.ContentTypeDefinitionController.java

public String copyAssetKey(String remoteSchemaValue, String localSchemaValue, String assetKey) {
    String newSchemaValue = localSchemaValue;

    try {/*from w ww.jav a2s  .  co m*/
        Document remoteDocument = createDocumentFromDefinition(remoteSchemaValue);
        Document localDocument = createDocumentFromDefinition(localSchemaValue);

        String attributeXPath = "/xs:schema/xs:simpleType[@name='assetKeys']/xs:restriction/xs:enumeration[@value='"
                + assetKey + "']";
        Node attributeNode = org.apache.xpath.XPathAPI.selectSingleNode(remoteDocument.getDocumentElement(),
                attributeXPath);

        String attributesXPath = "/xs:schema/xs:simpleType[@name='assetKeys']/xs:restriction";
        Node attributesNode = org.apache.xpath.XPathAPI.selectSingleNode(localDocument.getDocumentElement(),
                attributesXPath);
        if (attributesNode == null) {
            attributesNode = ContentTypeDefinitionController.getController()
                    .createNewEnumerationKey(localDocument, ContentTypeDefinitionController.ASSET_KEYS);
        }

        if (attributesNode != null && localDocument != null && attributeNode != null) {
            Node node = localDocument.importNode(attributeNode, true);
            attributesNode.appendChild(node);

            StringBuffer sb = new StringBuffer();
            org.infoglue.cms.util.XMLHelper.serializeDom(localDocument.getDocumentElement(), sb);
            newSchemaValue = sb.toString();
        } else {
            logger.error("Problem:" + attributesNode + " - " + localDocument + " - " + attributeNode);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return newSchemaValue;
}

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

/**
 * @param menuId/*  w w  w .  j a v a 2s  . com*/
 * @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.SiteAggregationMenuService.java

/**
 * Commiting temporary data.//from  www  .j  av  a2s.c o  m
 * @param menuType topmenu|sidemenu
 * @param forceUpdateMap
 * @throws Exception
 */
public synchronized void commitMenu(String menuType, Map<String, List<ForceUpdateUserPref>> forceUpdateMap,
        List<String> forceDeleteList, List<String> editSitetopIdList) throws Exception {
    ISPrincipal p = SecurityController.getPrincipalByType("UIDPrincipal");
    String myUid = p.getName();

    Siteaggregationmenu currentEntity = this.siteAggregationMenuDAO.select(menuType);

    Element currentMenuEl = currentEntity.getElement();
    Document currentDoc = currentMenuEl.getOwnerDocument();

    // Get the tree that the user edited
    List<Siteaggregationmenu_temp> myTempList = this.siteAggregationMenuTempDAO.selectByTypeAndUser(menuType,
            myUid);

    checkError(myTempList, editSitetopIdList, menuType);

    // Merge
    Element siteTop;
    WidgetDAO dao = WidgetDAO.newInstance();
    List<Element> deleteSiteTopList = new ArrayList<Element>();
    Siteaggregationmenu_temp orderTemp = null;

    for (Siteaggregationmenu_temp tempEntity : myTempList) {
        if (tempEntity.getId().getSitetopid().equals(SiteAggregationMenuTempDAO.SITEMENU_ORDER_TEMP_ID)) {
            orderTemp = tempEntity;
            continue;
        }

        // Update last modified time
        tempEntity.setLastmodified(new Date());
        this.siteAggregationMenuTempDAO.update(tempEntity);

        siteTop = tempEntity.getElement();
        String siteTopId = tempEntity.getId().getSitetopid();
        Node currentSiteTopEl = XPathAPI.selectSingleNode(currentMenuEl, "site-top[@id=\"" + siteTopId + "\"]");

        // Import
        Node mergeEl = currentDoc.importNode(siteTop.cloneNode(true), true);

        if (siteTop.getAttributeNode("deleteFlag") != null) {
            // If the tree is deleted
            if (currentSiteTopEl != null)
                deleteSiteTopList.add((Element) currentSiteTopEl);
            continue;
        } else {
            if (currentSiteTopEl != null) {
                currentDoc.getDocumentElement().replaceChild(mergeEl, currentSiteTopEl);
            } else {
                currentDoc.getDocumentElement().appendChild(mergeEl);
            }
        }

        // Properties should not be updated if existing data is not changed.
        if (currentSiteTopEl == null)
            continue;

        //Properties of url and authType in current menu is added to Map.
        NodeList sites = siteTop.getElementsByTagName("site");
        for (int i = 0; i < sites.getLength(); i++) {
            Element site = (Element) sites.item(i);
            String type = site.getAttribute("type");
            if (type == null)
                continue;

            String menuId = site.getAttribute("id");
            List<ForceUpdateUserPref> updatePropList = forceUpdateMap.get(menuId);
            if (updatePropList == null || updatePropList.isEmpty())
                continue;

            NodeList properties = XPathAPI.selectNodeList(site, "properties/property");

            Map<String, String> propMap = new HashMap<String, String>();
            for (int j = 0; j < properties.getLength(); j++) {
                Element property = (Element) properties.item(j);
                String name = property.getAttribute("name");
                String value = property.getFirstChild() != null ? property.getFirstChild().getNodeValue() : "";
                propMap.put(name, value);
            }

            String title = null;
            String href = null;
            Map<String, ForceUpdateUserPref> upPropMap = new HashMap<String, ForceUpdateUserPref>();
            Set<ForceUpdateUserPref> removePropNames = new HashSet<ForceUpdateUserPref>();
            for (ForceUpdateUserPref prop : updatePropList) {
                if ("__MENU_TITLE__".equals(prop.name)) {
                    title = site.getAttribute("title");
                } else if ("__MENU_HREF__".equals(prop.name)) {
                    href = site.getAttribute("href");
                } else {
                    String value = propMap.get(prop.name);
                    prop.value = value;
                    if (value != null) {
                        upPropMap.put(prop.name, prop);
                    } else {
                        removePropNames.add(prop);
                    }
                }
            }

            if (title != null || href != null || upPropMap.size() > 0 || removePropNames.size() > 0)
                dao.updateWidgetProperties(menuId, title, href, upPropMap, removePropNames);
        }
    }

    for (String menuId : forceDeleteList) {
        dao.deleteWidgetByMenuId(menuId);
    }
    // Deleting tree
    for (Element deleteSiteTop : deleteSiteTopList) {
        AdminServiceUtil.removeSelf(deleteSiteTop);
    }

    // Changing order of tree
    if (orderTemp != null) {
        Element orderEl = orderTemp.getElement();
        NodeList orderSiteTopList = orderEl.getElementsByTagName("site-top");

        for (int i = 0; i < orderSiteTopList.getLength(); i++) {
            Element orderSiteTop = (Element) orderSiteTopList.item(i);
            Element targetNode = (Element) XPathAPI.selectSingleNode(currentMenuEl,
                    "site-top[@id=\"" + orderSiteTop.getAttribute("id") + "\"]");

            if (targetNode != null)
                targetNode.getParentNode().appendChild(targetNode);
        }
    }

    //Apply the change of menu to widget.
    currentEntity.setElement(currentMenuEl);
    this.siteAggregationMenuDAO.update(currentEntity);
}

From source file:org.jasig.portal.layout.dlm.RDBMDistributedLayoutStore.java

/**
 * Method for acquiring copies of fragment layouts to assist in debugging.
 * No infrastructure code calls this but channels designed to expose the
 * structure of the cached fragments use this to obtain copies.
 * @return Map//ww w  . j a  v a2s .  com
 */
public Map<String, Document> getFragmentLayoutCopies()

{
    // since this is only visible in fragment list in administrative protlet, use default portal locale
    final Locale defaultLocale = LocaleManager.getPortalLocales()[0];
    final FragmentActivator activator = this.getFragmentActivator();

    final Map<String, Document> layouts = new HashMap<String, Document>();

    final List<FragmentDefinition> definitions = this.configurationLoader.getFragments();
    for (final FragmentDefinition fragmentDefinition : definitions) {
        final Document layout = DocumentFactory.getThreadDocument();
        final UserView userView = activator.getUserView(fragmentDefinition, defaultLocale);
        if (userView == null) {
            this.log.warn("No UserView found for FragmentDefinition " + fragmentDefinition.getName()
                    + ", it will be skipped.");
            continue;
        }
        final Node copy = layout.importNode(userView.layout.getDocumentElement(), true);
        layout.appendChild(copy);
        layouts.put(fragmentDefinition.getOwnerId(), layout);
    }
    return layouts;
}

From source file:org.jasig.portal.layout.simple.SimpleLayout.java

@Override
public void writeTo(Document document) throws PortalException {
    document.appendChild(document.importNode(layout.getDocumentElement(), true));
}

From source file:org.jasig.portal.layout.simple.SimpleLayout.java

@Override
public void writeTo(String nodeId, Document document) throws PortalException {
    document.appendChild(document.importNode(layout.getElementById(nodeId), true));
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Sets up an elements title, info and id based on the passed level.
 *
 * @param buildData Information and data structures for the build.
 * @param level     The level to build the root element is being built for.
 * @param doc       The document object the content is being added to.
 * @param ele/*w  w w  . ja  v a  2s  . c  om*/
 */
protected void setUpRootElement(final BuildData buildData, final Level level, final Document doc, Element ele) {
    final Element titleNode = doc.createElement("title");
    if (buildData.isTranslationBuild() && !isNullOrEmpty(level.getTranslatedTitle())) {
        titleNode.setTextContent(DocBookUtilities.escapeForXML(level.getTranslatedTitle()));
    } else {
        titleNode.setTextContent(DocBookUtilities.escapeForXML(level.getTitle()));
    }

    // Add the info if the container has one
    final Element infoElement;
    if (level.getInfoTopic() != null) {
        final InfoTopic infoTopic = level.getInfoTopic();
        final Node info = doc.importNode(infoTopic.getXMLDocument().getDocumentElement(), true);

        // Generate the info node
        final String elementInfoName;
        if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
            elementInfoName = "info";
        } else {
            elementInfoName = ele.getNodeName() + "info";
        }
        infoElement = doc.createElement(elementInfoName);

        // Move the contents of the info to the chapter/level
        final NodeList infoChildren = info.getChildNodes();
        while (infoChildren.getLength() > 0) {
            infoElement.appendChild(infoChildren.item(0));
        }
    } else {
        infoElement = null;
    }

    if (buildData.getDocBookVersion() == DocBookVersion.DOCBOOK_50) {
        ele.appendChild(titleNode);
        if (infoElement != null) {
            ele.appendChild(infoElement);
        }
    } else {
        if (infoElement != null) {
            ele.appendChild(infoElement);
        }
        ele.appendChild(titleNode);
    }

    DocBookBuildUtilities.setDOMElementId(buildData.getDocBookVersion(), ele,
            level.getUniqueLinkId(buildData.isUseFixedUrls()));
}

From source file:org.jboss.pressgang.ccms.contentspec.builder.DocBookBuilder.java

/**
 * Adds a Topics contents as the introduction text for a Level.
 *
 * @param docBookVersion/*from www. ja v  a  2 s.  c  o m*/
 * @param level          The level the intro topic is being added for.
 * @param specTopic      The Topic that contains the introduction content.
 * @param parentNode     The DOM parent node the intro content is to be appended to.
 * @param doc            The DOM Document the content is to be added to.
 */
protected void addTopicContentsToLevelDocument(final DocBookVersion docBookVersion, final Level level,
        final SpecTopic specTopic, final Element parentNode, final Document doc, final boolean includeInfo) {
    final Node section = doc.importNode(specTopic.getXMLDocument().getDocumentElement(), true);

    final String infoName;
    if (docBookVersion == DocBookVersion.DOCBOOK_50) {
        infoName = "info";
    } else {
        infoName = DocBookUtilities.TOPIC_ROOT_SECTIONINFO_NODE_NAME;
    }

    if (includeInfo && (level.getLevelType() != LevelType.PART)) {
        // Reposition the sectioninfo
        final List<Node> sectionInfoNodes = XMLUtilities.getDirectChildNodes(section, infoName);
        if (sectionInfoNodes.size() != 0) {
            final String parentInfoName;
            if (docBookVersion == DocBookVersion.DOCBOOK_50) {
                parentInfoName = "info";
            } else {
                parentInfoName = parentNode.getNodeName() + "info";
            }

            // Check if the parent already has a info node
            final List<Node> infoNodes = XMLUtilities.getDirectChildNodes(parentNode, parentInfoName);
            final Node infoNode;
            if (infoNodes.size() == 0) {
                infoNode = doc.createElement(parentInfoName);
                DocBookUtilities.setInfo(docBookVersion, (Element) infoNode, parentNode);
            } else {
                infoNode = infoNodes.get(0);
            }

            // Merge the info text
            final NodeList sectionInfoChildren = sectionInfoNodes.get(0).getChildNodes();
            final Node firstNode = infoNode.getFirstChild();
            while (sectionInfoChildren.getLength() > 0) {
                if (firstNode != null) {
                    infoNode.insertBefore(sectionInfoChildren.item(0), firstNode);
                } else {
                    infoNode.appendChild(sectionInfoChildren.item(0));
                }
            }
        }
    }

    // Remove the title and sectioninfo
    final List<Node> titleNodes = XMLUtilities.getDirectChildNodes(section,
            DocBookUtilities.TOPIC_ROOT_TITLE_NODE_NAME, infoName);
    for (final Node removeNode : titleNodes) {
        section.removeChild(removeNode);
    }

    // Move the contents of the section to the chapter/level
    final NodeList sectionChildren = section.getChildNodes();
    while (sectionChildren.getLength() > 0) {
        parentNode.appendChild(sectionChildren.item(0));
    }
}