Example usage for org.w3c.dom Element removeChild

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

Introduction

In this page you can find the example usage for org.w3c.dom Element removeChild.

Prototype

public Node removeChild(Node oldChild) throws DOMException;

Source Link

Document

Removes the child node indicated by oldChild from the list of children, and returns it.

Usage

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private void moveMenuItemUp(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalAdminException {

    String menuXML = (String) session.getAttribute("menuxml");
    Document doc = XMLTool.domparse(menuXML);

    String xpath = "//menuitem[@key = '" + formItems.getString("key") + "']";
    Element elem = (Element) XMLTool.selectNode(doc, xpath);

    Element parent = (Element) elem.getParentNode();
    Element previousSibling = (Element) elem.getPreviousSibling();
    elem = (Element) parent.removeChild(elem);
    doc.importNode(elem, true);// w  w  w  . j av a 2s .  c  o m

    if (previousSibling == null)
    // This is the top element, move it to the bottom
    {
        parent.appendChild(elem);
    } else {
        parent.insertBefore(elem, previousSibling);
    }

    session.setAttribute("menuxml", XMLTool.documentToString(doc));

    MultiValueMap queryParams = new MultiValueMap();
    queryParams.put("page", formItems.get("page"));
    queryParams.put("op", "browse");
    queryParams.put("keepxml", "yes");
    queryParams.put("highlight", formItems.get("key"));
    queryParams.put("menukey", formItems.get("menukey"));
    queryParams.put("parentmi", formItems.get("parentmi"));
    queryParams.put("subop", "shiftmenuitems");

    queryParams.put("move_menuitem", formItems.getString("move_menuitem", ""));
    queryParams.put("move_from_parent", formItems.getString("move_from_parent", ""));
    queryParams.put("move_to_parent", formItems.getString("move_to_parent", ""));

    redirectClientToAdminPath("adminpage", queryParams, request, response);
}

From source file:com.enonic.vertical.adminweb.MenuHandlerServlet.java

private void moveMenuItemDown(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        ExtendedMap formItems) throws VerticalAdminException {

    String menuXML = (String) session.getAttribute("menuxml");
    Document doc = XMLTool.domparse(menuXML);

    String xpath = "/model/menuitems-to-list//menuitem[@key = '" + formItems.getString("key") + "']";
    Element movingMenuItemElement = (Element) XMLTool.selectNode(doc, xpath);

    Element parentElement = (Element) movingMenuItemElement.getParentNode();
    Node nextSiblingElement = movingMenuItemElement.getNextSibling();

    movingMenuItemElement = (Element) parentElement.removeChild(movingMenuItemElement);
    doc.importNode(movingMenuItemElement, true);

    if (nextSiblingElement != null) {
        // spool forward...
        for (nextSiblingElement = nextSiblingElement.getNextSibling(); (nextSiblingElement != null
                && nextSiblingElement
                        .getNodeType() != Node.ELEMENT_NODE); nextSiblingElement = nextSiblingElement
                                .getNextSibling()) {

        }//  w w  w.ja va  2 s  .com

        if (nextSiblingElement != null) {
            parentElement.insertBefore(movingMenuItemElement, nextSiblingElement);
        } else {
            parentElement.appendChild(movingMenuItemElement);
        }
    } else {
        // This is the bottom element, move it to the top
        parentElement.insertBefore(movingMenuItemElement, parentElement.getFirstChild());
    }

    session.setAttribute("menuxml", XMLTool.documentToString(doc));

    MultiValueMap queryParams = new MultiValueMap();
    queryParams.put("page", formItems.get("page"));
    queryParams.put("op", "browse");
    queryParams.put("keepxml", "yes");
    queryParams.put("highlight", formItems.get("key"));
    queryParams.put("menukey", formItems.get("menukey"));
    queryParams.put("parentmi", formItems.get("parentmi"));
    queryParams.put("subop", "shiftmenuitems");

    queryParams.put("move_menuitem", formItems.getString("move_menuitem", ""));
    queryParams.put("move_from_parent", formItems.getString("move_from_parent", ""));
    queryParams.put("move_to_parent", formItems.getString("move_to_parent", ""));

    redirectClientToAdminPath("adminpage", queryParams, request, response);
}

From source file:org.gvnix.addon.jpa.addon.entitylistener.JpaOrmEntityListenerOperationsImpl.java

/**
 * Adjust listener order as is registered on
 * {@link JpaOrmEntityListenerRegistry}/*from   ww w  .  ja  va  2 s  . co  m*/
 * 
 * @param ormXml
 * @param entityListenerElement
 * @param entityListenerElements
 * @return true if xml elements had been changed
 */
private boolean adjustEntityListenerOrder(Document ormXml, Element entityListenerElement,
        List<Element> entityListenerElements) {

    // Prepare a Pair list which is a representation of current
    // entity-listener
    List<Pair<String, String>> currentOrder = new ArrayList<Pair<String, String>>();
    for (Element currentElement : entityListenerElements) {
        // Each Pair: key (left) = entity-listener class; value (right)
        // metadataProvider id
        currentOrder.add(ImmutablePair.of(currentElement.getAttribute(CLASS_ATTRIBUTE),
                getEntityListenerElementType(currentElement)));
    }

    // Create a comparator which can sort the list based on order configured
    // on registry
    ListenerOrderComparator comparator = new ListenerOrderComparator(registry.getListenerOrder());

    // Clone the Pair list and sort it
    List<Pair<String, String>> ordered = new ArrayList<Pair<String, String>>(currentOrder);
    Collections.sort(ordered, comparator);

    // Check if elements order is different form original
    boolean changeOrder = false;
    Pair<String, String> currentPair, orderedPair;
    for (int i = 0; i < currentOrder.size(); i++) {
        currentPair = currentOrder.get(i);
        orderedPair = ordered.get(i);
        if (!StringUtils.equals(currentPair.getKey(), orderedPair.getKey())) {
            changeOrder = true;
            break;
        }
    }

    if (!changeOrder) {
        // Order is correct: nothing to do
        return false;
    }

    // List for new elements to add
    List<Node> newList = new ArrayList<Node>(entityListenerElements.size());

    // Iterate over final ordered list
    int curIndex;
    Node cloned, old;
    for (int i = 0; i < ordered.size(); i++) {
        orderedPair = ordered.get(i);
        // Gets old listener XML node
        curIndex = indexOfListener(entityListenerElements, orderedPair.getKey());
        old = entityListenerElements.get(curIndex);

        // Clone old node and add to new elements list
        cloned = old.cloneNode(true);
        newList.add(cloned);

        // Remove old listener node from parent
        entityListenerElement.removeChild(old);
    }

    // Add listeners xml nodes to parent again in final order
    for (Node node : newList) {
        entityListenerElement.appendChild(node);
    }

    return true;
}

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void handleFileElement(String pid, int itemIndex, Element fileElement)
        throws URISyntaxException, IOException, FedoraClientException, XPathExpressionException {
    Node tempFile = fileElement.getElementsByTagName("TempFile").item(0);
    Node pathName = fileElement.getElementsByTagName("PathName").item(0);
    if (tempFile == null || pathName == null) {
        return;/*w  ww  .j a v a2 s.  co  m*/
    }

    String id = pid.substring("qucosa:".length());
    String tmpFileName = tempFile.getTextContent();
    String targetFilename = pathName.getTextContent();
    URI fileUri = fileHandlingService.copyTempfileToTargetFileSpace(tmpFileName, targetFilename, id);

    Node labelNode = fileElement.getElementsByTagName("Label").item(0);
    String label = (labelNode != null) ? labelNode.getTextContent() : "";

    final Path filePath = new File(fileUri).toPath();

    String detectedContentType = Files.probeContentType(filePath);
    if (!(Boolean) xPath.evaluate("MimeType[text()!='']", fileElement, XPathConstants.BOOLEAN)) {
        if (detectedContentType != null) {
            Element mimeTypeElement = fileElement.getOwnerDocument().createElement("MimeType");
            mimeTypeElement.setTextContent(detectedContentType);
            fileElement.appendChild(mimeTypeElement);
        }
    }

    if (!(Boolean) xPath.evaluate("FileSize[text()!='']", fileElement, XPathConstants.BOOLEAN)) {
        Element fileSizeElement = fileElement.getOwnerDocument().createElement("FileSize");
        fileSizeElement.setTextContent(String.valueOf(Files.size(filePath)));
        fileElement.appendChild(fileSizeElement);
    }

    String dsid = DSID_QUCOSA_ATT + (itemIndex);
    String state = determineDatastreamState(fileElement);
    DatastreamProfile dsp = fedoraRepository.createExternalReferenceDatastream(pid, dsid, label, fileUri,
            detectedContentType, state);
    fileElement.setAttribute("id", String.valueOf(itemIndex));
    addHashValue(fileElement, dsp);

    fileElement.removeChild(tempFile);
}

From source file:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java

/**
 * Adds XSD element definition created from the midPoint PropertyDefinition.
 * @param definition midPoint PropertyDefinition
 * @param parent element under which the definition will be added
 *///from ww w.  ja va  2  s . com
private void addPropertyDefinition(PrismPropertyDefinition definition, Element parent) {
    Element property = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "element"));
    // Add to document first, so following methods will be able to resolve namespaces
    parent.appendChild(property);

    String attrNamespace = definition.getName().getNamespaceURI();
    if (attrNamespace != null && attrNamespace.equals(getNamespace())) {
        setAttribute(property, "name", definition.getName().getLocalPart());
        setQNameAttribute(property, "type", definition.getTypeName());
    } else {
        setQNameAttribute(property, "ref", definition.getName());
    }

    if (definition.getMinOccurs() != 1) {
        setAttribute(property, "minOccurs", Integer.toString(definition.getMinOccurs()));
    }

    if (definition.getMaxOccurs() != 1) {
        String maxOccurs = definition.getMaxOccurs() == XSParticle.UNBOUNDED ? MAX_OCCURS_UNBOUNDED
                : Integer.toString(definition.getMaxOccurs());
        setAttribute(property, "maxOccurs", maxOccurs);
    }

    Element annotation = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation"));
    property.appendChild(annotation);
    Element appinfo = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"));
    annotation.appendChild(appinfo);

    addCommonDefinitionAnnotations(definition, appinfo);

    if (!definition.canAdd() || !definition.canRead() || !definition.canModify()) {
        // read-write-create attribute is the default. If any of this flags is missing, we must
        // add appropriate annotations.
        if (definition.canAdd()) {
            addAnnotation(A_ACCESS, A_ACCESS_CREATE, appinfo);
        }
        if (definition.canRead()) {
            addAnnotation(A_ACCESS, A_ACCESS_READ, appinfo);
        }
        if (definition.canModify()) {
            addAnnotation(A_ACCESS, A_ACCESS_UPDATE, appinfo);
        }
    }

    if (definition.isIndexed() != null) {
        addAnnotation(A_INDEXED, XmlTypeConverter.toXmlTextContent(definition.isIndexed(), A_INDEXED), appinfo);
    }

    SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
    definitionFactory.addExtraPropertyAnnotations(definition, appinfo, this);

    if (!appinfo.hasChildNodes()) {
        // remove unneeded <annotation> element
        property.removeChild(annotation);
    }
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

public final Document getContentDocument(AdminService admin, User user, int contentKey, int categoryKey,
        int versionKey, Integer populateContentDataFromVersion) {
    Document asW3cDoc;/*from  w  w w.  jav  a 2s  . c om*/

    if (contentKey != -1) {
        CategoryAccessResolver categoryAccessResolver = new CategoryAccessResolver(groupDao);
        ContentAccessResolver contentAccessResolver = new ContentAccessResolver(groupDao);

        ContentXMLCreator contentXMLCreator = new ContentXMLCreator();
        contentXMLCreator.setIncludeAccessRightsInfo(true);
        contentXMLCreator.setIncludeUserRightsInfo(true, categoryAccessResolver, contentAccessResolver);
        contentXMLCreator.setIncludeUserRightsInfoForRelated(true, categoryAccessResolver,
                contentAccessResolver);
        contentXMLCreator.setIncludeVersionsInfoForAdmin(true);
        contentXMLCreator.setIncludeRelatedContentsInfo(true);
        contentXMLCreator.setIncludeRepositoryPathInfo(true);
        contentXMLCreator.setIncludeAssignment(true);
        contentXMLCreator.setIncludeDraftInfo(true);
        contentXMLCreator.setOrderByCreatedAtDescending(true);

        ContentVersionEntity version = contentVersionDao.findByKey(new ContentVersionKey(versionKey));

        ContentVersionEntity versionToPopulateContentDataFrom;
        if (populateContentDataFromVersion != null && !populateContentDataFromVersion.equals(versionKey)) {
            versionToPopulateContentDataFrom = contentVersionDao
                    .findByKey(new ContentVersionKey(populateContentDataFromVersion));
        } else {
            versionToPopulateContentDataFrom = version;
        }

        UserEntity runningUser = securityService.getUser(user);

        RelatedChildrenContentQuery relatedChildrenContentQuery = new RelatedChildrenContentQuery(
                timeService.getNowAsDateTime().toDate());
        relatedChildrenContentQuery.setContentVersion(versionToPopulateContentDataFrom);
        relatedChildrenContentQuery.setChildrenLevel(1);
        relatedChildrenContentQuery.setIncludeOffline();
        /*
         * Include related content even if running user doesn't have access - if not the user will not see related content.
         */
        relatedChildrenContentQuery.setUser(null);

        RelatedContentResultSet relatedContents = contentService
                .queryRelatedContent(relatedChildrenContentQuery);
        XMLDocument contentsDocAsXMLDocument = contentXMLCreator.createContentsDocument(runningUser, version,
                relatedContents);
        if (populateContentDataFromVersion != null && !populateContentDataFromVersion.equals(versionKey)) {
            // Fetching the content-XML without related content.  This XML is only used to get the elements from
            // the version to populate from, and replacing them in the draft version which is being edited.
            org.jdom.Document contentsDocAsJdomDocument = contentsDocAsXMLDocument.getAsJDOMDocument();
            org.jdom.Document contentXmlFromVersionToPopulateFrom = contentXMLCreator
                    .createContentsDocument(runningUser, versionToPopulateContentDataFrom, null)
                    .getAsJDOMDocument();

            org.jdom.Element contentElInOriginal = contentsDocAsJdomDocument.getRootElement()
                    .getChild("content");

            // Replace <contentdata>
            org.jdom.Element contentdataElInVersionToPopulateFrom = contentXmlFromVersionToPopulateFrom
                    .getRootElement().getChild("content").getChild("contentdata");
            contentElInOriginal.removeChild("contentdata");
            contentElInOriginal.addContent(contentdataElInVersionToPopulateFrom.detach());

            // Replace <binaries>
            org.jdom.Element binariesElInVersionToPopulateFrom = contentXmlFromVersionToPopulateFrom
                    .getRootElement().getChild("content").getChild("binaries");
            contentElInOriginal.removeChild("binaries");
            contentElInOriginal.addContent(binariesElInVersionToPopulateFrom.detach());

            asW3cDoc = XMLDocumentFactory.create(contentsDocAsJdomDocument).getAsDOMDocument();

        } else {
            asW3cDoc = contentsDocAsXMLDocument.getAsDOMDocument();
        }
    } else {
        // Blank form, make dummy document
        asW3cDoc = XMLTool.createDocument("contents");
        String xmlAccessRights = admin.getDefaultAccessRights(user, AccessRight.CONTENT, categoryKey);
        XMLTool.mergeDocuments(asW3cDoc, xmlAccessRights, true);
    }

    return asW3cDoc;
}

From source file:com.evolveum.midpoint.prism.schema.SchemaToDomProcessor.java

/**
 * Adds XSD complexType definition from the midPoint Schema ComplexTypeDefinion object
 * @param definition midPoint Schema ComplexTypeDefinion object
 * @param parent element under which the definition will be added
 * @return created (and added) XSD complexType definition
 *//*from  w  w w .  j ava 2 s .c o m*/
private Element addComplexTypeDefinition(ComplexTypeDefinition definition, Element parent) {

    if (definition == null) {
        // Nothing to do
        return null;
    }
    if (definition.getTypeName() == null) {
        throw new UnsupportedOperationException("Anonymous complex types as containers are not supported yet");
    }

    Element complexType = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "complexType"));
    parent.appendChild(complexType);
    // "typeName" should be used instead of "name" when defining a XSD type
    setAttribute(complexType, "name", definition.getTypeName().getLocalPart());
    Element annotation = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "annotation"));
    complexType.appendChild(annotation);

    Element containingElement = complexType;
    if (definition.getSuperType() != null) {
        Element complexContent = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "complexContent"));
        complexType.appendChild(complexContent);
        Element extension = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "extension"));
        complexContent.appendChild(extension);
        setQNameAttribute(extension, "base", definition.getSuperType());
        containingElement = extension;
    }

    Element sequence = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "sequence"));
    containingElement.appendChild(sequence);

    Collection<? extends ItemDefinition> definitions = definition.getDefinitions();
    for (ItemDefinition def : definitions) {
        if (def instanceof PrismPropertyDefinition) {
            addPropertyDefinition((PrismPropertyDefinition) def, sequence);
        } else if (def instanceof PrismContainerDefinition) {
            PrismContainerDefinition contDef = (PrismContainerDefinition) def;
            addContainerDefinition(contDef, sequence, parent);
        } else if (def instanceof PrismReferenceDefinition) {
            addReferenceDefinition((PrismReferenceDefinition) def, sequence);
        } else {
            throw new IllegalArgumentException("Uknown definition " + def + "(" + def.getClass().getName()
                    + ") in complex type definition " + def);
        }
    }

    if (definition.isXsdAnyMarker()) {
        addXsdAnyDefinition(sequence);
    }

    Element appinfo = createElement(new QName(W3C_XML_SCHEMA_NS_URI, "appinfo"));
    annotation.appendChild(appinfo);

    if (definition.isObjectMarker()) {
        // annotation: propertyContainer
        addAnnotation(A_OBJECT, definition.getDisplayName(), appinfo);
    } else if (definition.isContainerMarker()) {
        // annotation: propertyContainer
        addAnnotation(A_PROPERTY_CONTAINER, definition.getDisplayName(), appinfo);
    }

    addCommonDefinitionAnnotations(definition, appinfo);

    SchemaDefinitionFactory definitionFactory = getDefinitionFactory();
    definitionFactory.addExtraComplexTypeAnnotations(definition, appinfo, this);

    if (!appinfo.hasChildNodes()) {
        // remove unneeded <annotation> element
        complexType.removeChild(annotation);
    }

    return complexType;
}

From source file:com.enonic.vertical.adminweb.handlers.ContentBaseHandlerServlet.java

private void handlerPreviewSiteList(HttpServletRequest request, HttpServletResponse response,
        AdminService admin, ExtendedMap formItems, User user)
        throws VerticalAdminException, VerticalEngineException {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("page", formItems.get("page"));
    int unitKey = formItems.getInt("selectedunitkey", -1);
    int siteKey = formItems.getInt("menukey", -1);

    int contentKey = formItems.getInt("contentkey", -1);
    int contentTypeKey;
    if (contentKey >= 0) {
        parameters.put("contentkey", contentKey);
        contentTypeKey = admin.getContentTypeKey(contentKey);
        parameters.put("sessiondata", formItems.getBoolean("sessiondata", false));
    } else {/*from w  ww.  ja v  a 2 s  .  c  om*/
        contentTypeKey = formItems.getInt("contenttypekey", -1);
    }
    parameters.put("contenttypekey", contentTypeKey);

    int versionKey = formItems.getInt("versionkey", -1);
    if (versionKey != -1) {
        parameters.put("versionkey", versionKey);
    }

    Document doc = XMLTool.domparse(admin.getAdminMenu(user, -1));
    Element rootSitesElement = doc.getDocumentElement();
    Element[] allSiteElements = XMLTool.getElements(rootSitesElement);
    int defaultPageTemplateKey = -1;
    if (allSiteElements.length > 0) {
        TreeMap<String, Element> allSitesMap = new TreeMap<String, Element>();
        for (Element siteElement : allSiteElements) {
            int mKey = Integer.valueOf(siteElement.getAttribute("key"));
            if (admin.hasContentPageTemplates(mKey, contentTypeKey)) {
                String name = siteElement.getAttribute("name");
                allSitesMap.put(name, siteElement);
            }
            rootSitesElement.removeChild(siteElement);
        }

        if (allSitesMap.size() > 0) {
            Element firstMenuElem = allSitesMap.get(allSitesMap.firstKey());
            if (siteKey < 0) {
                siteKey = Integer.valueOf(firstMenuElem.getAttribute("key"));
            }

            for (Element siteElement : allSitesMap.values()) {
                rootSitesElement.appendChild(siteElement);
                int key = Integer.parseInt(siteElement.getAttribute("key"));
                if (key == siteKey) {
                    String defaultPageTemplateAttr = siteElement.getAttribute("defaultpagetemplate");
                    if (defaultPageTemplateAttr != null && !defaultPageTemplateAttr.equals("")) {
                        defaultPageTemplateKey = Integer.parseInt(defaultPageTemplateAttr);
                    }

                }
            }
        }
    }

    addCommonParameters(admin, user, request, parameters, unitKey, siteKey);

    if (siteKey >= 0) {
        int[] excludeTypeKeys = { 1, 2, 3, 4, 6 };
        String pageTemplateXML = admin.getPageTemplatesByMenu(siteKey, excludeTypeKeys);
        Document ptDoc = XMLTool.domparse(pageTemplateXML);
        XMLTool.mergeDocuments(doc, ptDoc, true);

        if (contentKey >= 0) {
            Document chDoc = XMLTool.domparse(admin.getContentHomes(contentKey));
            XMLTool.mergeDocuments(doc, chDoc, true);
        }

        if (formItems.containsKey("pagetemplatekey")) {
            int pageTemplateKey = formItems.getInt("pagetemplatekey");
            parameters.put("pagetemplatekey", String.valueOf(pageTemplateKey));
        } else {
            if (contentTypeKey >= 0) {
                org.jdom.Document pageTemplateDocument = XMLTool.jdomparse(pageTemplateXML);
                org.jdom.Element root = pageTemplateDocument.getRootElement();
                List<org.jdom.Element> pageTemplates = root.getChildren("pagetemplate");
                Set<KeyValue> pageTemplateKeys = new HashSet<KeyValue>();
                for (org.jdom.Element pageTemplate : pageTemplates) {

                    int pageTemplateKey = Integer.parseInt(pageTemplate.getAttribute("key").getValue());
                    org.jdom.Element contentTypesNode = pageTemplate.getChild("contenttypes");
                    List<org.jdom.Element> contentTypeElements = contentTypesNode.getChildren("contenttype");

                    if (checkMatchingContentType(contentTypeKey, contentTypeElements)) {
                        KeyValue keyValue = new KeyValue(pageTemplateKey, pageTemplate.getChildText("name"));
                        pageTemplateKeys.add(keyValue);
                    }
                }
                if (pageTemplateKeys.size() > 0) {
                    KeyValue[] keys = new KeyValue[pageTemplateKeys.size()];
                    keys = pageTemplateKeys.toArray(keys);
                    Arrays.sort(keys);
                    parameters.put("pagetemplatekey", keys[0].key);
                } else {
                    if (defaultPageTemplateKey < 0) {
                        throw new VerticalAdminException("Unable to resolve page template. "
                                + "No matching page template found and default page template is not set.");
                    }
                    parameters.put("pagetemplatekey", String.valueOf(defaultPageTemplateKey));
                }

            }
        }

        if (formItems.containsKey("menuitemkey")) {
            parameters.put("menuitemkey", formItems.get("menuitemkey"));
        }
    }

    transformXML(request, response, doc, "contenttype_preview_list.xsl", parameters);
}

From source file:lcmc.data.VMSXML.java

/** Modify xml of some device element. */
private void modifyXML(final Node domainNode, final String domainName, final Map<String, String> tagMap,
        final Map<String, String> attributeMap, final Map<String, String> parametersMap, final String path,
        final String elementName, final VirtualHardwareComparator vhc) {
    final String configName = namesConfigsMap.get(domainName);
    if (configName == null) {
        return;//  ww w  .  j av a2s  . co  m
    }
    //final Node domainNode = getDomainNode(domainName);
    if (domainNode == null) {
        return;
    }
    final XPath xpath = XPathFactory.newInstance().newXPath();
    final Node devicesNode = getDevicesNode(xpath, domainNode);
    if (devicesNode == null) {
        return;
    }
    try {
        final NodeList nodes = (NodeList) xpath.evaluate(path, domainNode, XPathConstants.NODESET);
        Element hwNode = vhc.getElement(nodes, parametersMap);
        if (hwNode == null) {
            hwNode = (Element) devicesNode
                    .appendChild(domainNode.getOwnerDocument().createElement(elementName));
        }
        for (final String param : parametersMap.keySet()) {
            final String value = parametersMap.get(param);
            if (!tagMap.containsKey(param) && attributeMap.containsKey(param)) {
                /* attribute */
                final Node attributeNode = hwNode.getAttributes().getNamedItem(attributeMap.get(param));
                if (attributeNode == null) {
                    if (value != null && !"".equals(value)) {
                        hwNode.setAttribute(attributeMap.get(param), value);
                    }
                } else if (value == null || "".equals(value)) {
                    hwNode.removeAttribute(attributeMap.get(param));
                } else {
                    attributeNode.setNodeValue(value);
                }
                continue;
            }
            Element node = (Element) getChildNode(hwNode, tagMap.get(param));
            if ((attributeMap.containsKey(param) || "True".equals(value)) && node == null) {
                node = (Element) hwNode
                        .appendChild(domainNode.getOwnerDocument().createElement(tagMap.get(param)));
            } else if (node != null && !attributeMap.containsKey(param)
                    && (value == null || "".equals(value))) {
                hwNode.removeChild(node);
            }
            if (attributeMap.containsKey(param)) {
                final Node attributeNode = node.getAttributes().getNamedItem(attributeMap.get(param));
                if (attributeNode == null) {
                    if (value != null && !"".equals(value)) {
                        node.setAttribute(attributeMap.get(param), value);
                    }
                } else {
                    if (value == null || "".equals(value)) {
                        node.removeAttribute(attributeMap.get(param));
                    } else {
                        attributeNode.setNodeValue(value);
                    }
                }
            }
        }
        final Element hwAddressNode = (Element) getChildNode(hwNode, HW_ADDRESS);
        if (hwAddressNode != null) {
            hwNode.removeChild(hwAddressNode);
        }
    } catch (final javax.xml.xpath.XPathExpressionException e) {
        Tools.appError("could not evaluate: ", e);
        return;
    }
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private void copyMenu(CopyContext copyContext, Element menuElem) throws VerticalCopyException,
        VerticalCreateException, VerticalUpdateException, VerticalSecurityException {

    if (menuElem != null) {
        User user = copyContext.getUser();
        int oldMenuKey = Integer.parseInt(menuElem.getAttribute("key"));

        //if (copyContext.getOldSiteKey() != copyContext.getNewSiteKey())
        //  menuElem.setAttribute("sitekey", String.valueOf(copyContext.getNewSiteKey()));
        //else {//from w ww  .ja v  a2s .  co  m
        Element nameElem = XMLTool.getElement(menuElem, "name");
        Text text = (Text) nameElem.getFirstChild();
        Map translationMap = languageMap.getTranslationMap(user.getSelectedLanguageCode());
        text.setData(text.getData() + " (" + translationMap.get("%txtCopy%") + ")");
        //}

        Element elem = XMLTool.getElement(menuElem, "firstpage");
        String oldFirstPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        elem = XMLTool.getElement(menuElem, "loginpage");
        String oldLoginPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        elem = XMLTool.getElement(menuElem, "errorpage");
        String oldErrorPageKey = elem.getAttribute("key");
        elem.removeAttribute("key");

        String oldDefaultPageTemplateKey = null;
        elem = XMLTool.getElement(menuElem, "defaultpagetemplate");
        if (elem != null) {
            oldDefaultPageTemplateKey = elem.getAttribute("pagetemplatekey");
            elem.removeAttribute("pagetemplatekey");
        }

        Document newDoc = XMLTool.createDocument();
        Element newMenuElem = (Element) newDoc.importNode(menuElem, true);
        newDoc.appendChild(newMenuElem);
        Element menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
        newMenuElem.removeChild(menuitemsElem);
        SiteKey menuKey = createMenu(user, copyContext, newDoc, false);

        // copy content objects and page templates
        ContentObjectHandler contentObjectHandler = getContentObjectHandler();
        contentObjectHandler.copyContentObjects(oldMenuKey, copyContext);
        PageTemplateHandler pageTemplateHandler = getPageTemplateHandler();
        pageTemplateHandler.copyPageTemplates(oldMenuKey, copyContext);

        Document doc = getMenu(user, menuKey.toInt(), true, true);
        Element docElem = doc.getDocumentElement();
        newMenuElem = (Element) docElem.getFirstChild();
        doc.replaceChild(newMenuElem, docElem);
        Element newMenuitemsElem = (Element) doc.importNode(menuitemsElem, true);
        menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
        newMenuElem.replaceChild(newMenuitemsElem, menuitemsElem);

        // prepare copy of menu items
        prepareCopy(newMenuitemsElem, copyContext);
        updateMenu(user, copyContext, doc, false);

        if (oldFirstPageKey != null && oldFirstPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "firstpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldFirstPageKey))));
        }

        if (oldLoginPageKey != null && oldLoginPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "loginpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldLoginPageKey))));
        }

        if (oldErrorPageKey != null && oldErrorPageKey.length() > 0) {
            elem = XMLTool.createElementIfNotPresent(doc, newMenuElem, "errorpage");
            elem.setAttribute("key",
                    String.valueOf(copyContext.getMenuItemKey(Integer.parseInt(oldErrorPageKey))));
        }

        if (oldDefaultPageTemplateKey != null && oldDefaultPageTemplateKey.length() > 0) {
            elem = XMLTool.createElement(doc, newMenuElem, "defaultpagetemplate");
            elem.setAttribute("pagetemplatekey", String
                    .valueOf(copyContext.getPageTemplateKey(Integer.parseInt(oldDefaultPageTemplateKey))));
        }

        if (copyContext.isIncludeContents()) {
            menuitemsElem = XMLTool.getElement(newMenuElem, "menuitems");
            prepareUpdate(menuitemsElem);
        }

        // update default css
        Element menudataElem = XMLTool.getElement(newMenuElem, "menudata");
        Element defaultcssElem = XMLTool.getElement(menudataElem, "defaultcss");
        if (defaultcssElem != null) {
            String cssKey = defaultcssElem.getAttribute("key");
            if (cssKey != null && cssKey.length() > 0) {
                defaultcssElem.setAttribute("key", cssKey);
            }
        }

        updateMenu(user, copyContext, doc, true);

        // post-process content objects and page templates
        contentObjectHandler.copyContentObjectsPostOp(oldMenuKey, copyContext);
        pageTemplateHandler.copyPageTemplatesPostOp(oldMenuKey, copyContext);
    }
}