Example usage for org.w3c.dom Element replaceChild

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

Introduction

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

Prototype

public Node replaceChild(Node newChild, Node oldChild) throws DOMException;

Source Link

Document

Replaces the child node oldChild with newChild in the list of children, and returns the oldChild node.

Usage

From source file:com.mirth.connect.model.util.ImportConverter.java

public static Document convertServerConfiguration(String serverConfiguration) throws Exception {
    serverConfiguration = convertPackageNames(serverConfiguration);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    Document document;/*from  w  w w. j  a  v  a  2  s .com*/
    DocumentBuilder builder;

    builder = factory.newDocumentBuilder();
    document = builder.parse(new InputSource(new StringReader(serverConfiguration)));

    // Remove users from the server configuration file if they were there.
    Element documentElement = document.getDocumentElement();
    NodeList users = documentElement.getElementsByTagName("users");
    if (users != null && users.getLength() > 0) {
        documentElement.removeChild(users.item(0));
    }

    Element channelsRoot = (Element) document.getElementsByTagName("channels").item(0);
    NodeList channels = getElements(document, "channel", "com.mirth.connect.model.Channel");
    List<Element> channelList = new ArrayList<Element>();
    int length = channels.getLength();

    for (int i = 0; i < length; i++) {
        // Must get node 0 because the first channel is removed each
        // iteration
        Element channel = (Element) channels.item(0);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer trans = tf.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        StringWriter sw = new StringWriter();
        trans.transform(new DOMSource(channel), new StreamResult(sw));
        String channelDocXML = sw.toString();

        channelList.add(new DonkeyElement(convertChannelString(channelDocXML)).getElement());
        channelsRoot.removeChild(channel);
    }

    for (Element channel : channelList) {
        channelsRoot.appendChild(document.importNode(channel, true));
    }

    NodeList codeTemplates = documentElement.getElementsByTagName("codeTemplates");
    int codeTemplateCount = codeTemplates.getLength();

    for (int i = 0; i < codeTemplateCount; i++) {
        Element codeTemplate = (Element) codeTemplates.item(i);
        Element convertedCodeTemplate = convertCodeTemplates(new DonkeyElement(codeTemplate).toXml())
                .getDocumentElement();
        documentElement.replaceChild(document.importNode(convertedCodeTemplate, true), codeTemplate);
    }

    return document;
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

/**
 * Thread-safety tested/* w ww.j  a v a2  s .  co m*/
 */
@Override
public Map<String, Object> updateElementByPathById(String path, final String originalXml, String elementId,
        final String elementXml) throws SAXException, IOException {

    Assert.hasText(path);
    Assert.hasText(elementId);
    Assert.hasText(originalXml);
    Assert.hasText(elementId);

    Document originalDom = parse(originalXml);

    Document elementDom = parse(elementXml);

    Document finalDom = originalDom;

    Element finalDomRoot = (Element) finalDom.getFirstChild();

    Element elementRoot = (Element) elementDom.getFirstChild();

    List<String> nodeList = getNodeList(path);
    logger.trace("nodeList: " + nodeList + " =? ");

    // the root node of the path should be the same as the root node of
    // the originalXml
    Assert.isTrue(nodeList.size() > 0 && nodeList.get(0).equals(finalDomRoot.getNodeName()));

    // remove first one, should be protocol
    nodeList.remove(0);

    String elementToDeleteName = nodeList.get(nodeList.size() - 1);

    logger.trace("adding <" + elementToDeleteName + ">");
    // remove last one, should be <drug>, we are attaching the drug into
    // drugs... so we want the rightmost element to be drugs...
    nodeList.remove(nodeList.size() - 1);

    Element currentNode = finalDomRoot;
    int c = 0;
    for (String n : nodeList) {
        NodeList cur = currentNode.getElementsByTagName(n);

        c = cur.getLength();

        if (c > 1) {
            throw new RuntimeException("illeagl xml structure; find " + c + " elements with name " + n);
        }

        if (c == 0) {
            throw new RuntimeException("illeagl xml structure; " + n + " doesn't exist");
        }

        currentNode = (Element) cur.item(0);

    }

    logger.trace("rightmost element: " + currentNode.getNodeName());

    elementRoot.setAttribute("id", elementId);

    Node newChild = finalDom.importNode(elementRoot, true);
    NodeList nodes = currentNode.getChildNodes();

    int l = nodes.getLength();

    logger.trace("lenght: " + l);

    for (int i = 0; i < l; i++) {
        Element cc = (Element) nodes.item(i);

        if (cc.getAttribute("id").equals(elementId)) {
            currentNode.replaceChild(newChild, cc);
            break;
        }
    }

    Map<String, Object> resultMap = new HashMap<String, Object>(3);
    resultMap.put("finalXml", DomUtils.elementToString(finalDom));
    resultMap.put("elementXml", DomUtils.elementToString(elementDom));
    resultMap.put("elementId", elementId);
    return resultMap;
}

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

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

    int menuKey = formItems.getInt("menukey");

    User user = securityService.getLoggedInAdminConsoleUser();
    String menuXML = admin.getAdminMenu(user, menuKey);

    boolean forwardData = formItems.getBoolean("forward_data", false);
    boolean create;

    String menuItemXML = null;//from   w ww  . ja  v a2  s  .  c o m
    String categoryXML = null;
    String pageTemplatesXML;
    String pageTemplateParamsXML = null;
    String defaultAccessRightXML = null;

    // menuitem key:
    String key = formItems.getString("key", null);

    try {
        if (key != null && !key.startsWith("f") && !key.equals("none")) {
            create = false;
            menuItemXML = admin.getMenuItem(user, Integer.parseInt(key), false, true);
        } else {
            create = true;
            String insertBelow = formItems.getString("insertbelow", null);
            if (insertBelow != null && !"-1".equals(insertBelow)) {
                defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM,
                        Integer.parseInt(insertBelow), true);
            } else {
                defaultAccessRightXML = admin.getAccessRights(user, AccessRight.MENUITEM_DEFAULT, menuKey,
                        true);
            }
        }

        int[] excludeTypeKeys = null; // before we excluded page-tempales of type newsletter, but not anymore.
        pageTemplatesXML = admin.getPageTemplatesByMenu(menuKey, excludeTypeKeys);

        Document doc1 = XMLTool.domparse(menuXML);
        Element menuElem = XMLTool.selectElement(doc1.getDocumentElement(), "//menu[@key = '" + menuKey + "']");

        int pageTemplateKey = formItems.getInt("selpagetemplatekey", -1);
        if (pageTemplateKey < 0 && create) {
            // selpagetemplatekey has not been set... set it to parent or default
            // pagetemplatekey (if appliccable)
            int insertBelow = -1;
            if (formItems.containsKey("insertbelow")
            /* && formItems.get("insertbelow") instanceof Integer */ ) {
                insertBelow = formItems.getInt("insertbelow");
            }

            pageTemplateKey = findParentPagetemplateKey(doc1, insertBelow);
            formItems.putInt("selpagetemplatekey", pageTemplateKey);
        }

        if (pageTemplateKey >= 0) {
            pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
        } else if (menuItemXML != null
                && XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey") != null) {
            pageTemplateKey = Integer.parseInt(XMLTool.getElementText(menuItemXML, "//page/@pagetemplatekey"));
            pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
        } else {
            String tmp = menuElem.getAttribute("defaultpagetemplate");
            if (tmp != null && tmp.length() > 0) {
                pageTemplateKey = Integer.parseInt(tmp);
                pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
            }
        }

        // insert correct menuitem XML:
        Element menuitemElem = null;
        if (menuItemXML != null) {
            Document miDoc = XMLTool.domparse(menuItemXML);
            Element tmpElem = miDoc.getDocumentElement();
            tmpElem = XMLTool.getFirstElement(tmpElem);

            if (tmpElem != null) {
                // add read count
                // int readCount = admin.getReadCount(LogHandler.TABLE_TMENUITEM, Integer.parseInt(key));
                // Element elem = XMLTool.createElement(miDoc, tmpElem, "logentries");
                // elem.setAttribute("totalread", String.valueOf(readCount));

                if (tmpElem != null) {
                    String xpath = "//menuitem[@key = '" + key + "']";
                    Element oldElem = (Element) XMLTool.selectNode(doc1.getDocumentElement(), xpath);
                    if (oldElem != null) {
                        Element menuitemsElem = (Element) oldElem.getParentNode();
                        menuitemElem = (Element) doc1.importNode(tmpElem, true);
                        menuitemsElem.replaceChild(menuitemElem, oldElem);
                    }
                }
            }
        }

        Document pageTemplateDoc = XMLTool.domparse(pageTemplatesXML);

        XMLTool.mergeDocuments(doc1, pageTemplateDoc, true);

        if (defaultAccessRightXML != null) {
            XMLTool.mergeDocuments(doc1, XMLTool.domparse(defaultAccessRightXML), true);
        }

        ExtendedMap parameters = new ExtendedMap();

        if (forwardData) {
            // get accessrights element
            Node nodeAccessRights;
            if (create) {
                nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(), "/menus/accessrights");
            } else {
                nodeAccessRights = XMLTool.selectNode(doc1.getDocumentElement(),
                        "//menuitem[@key=" + key + "]/accessrights");
            }

            // get new accessrights xml from parameters
            String xmlAccessRights = buildAccessRightsXML(formItems);
            if (xmlAccessRights != null) {
                Document docAccessRights = XMLTool.domparse(xmlAccessRights);

                if (docAccessRights.getDocumentElement().hasChildNodes())
                // replace accessrights element with the generated accessrights
                {
                    nodeAccessRights.getParentNode().replaceChild(
                            doc1.importNode(docAccessRights.getDocumentElement(), true), nodeAccessRights);
                }
            }

            // get custom parameters
            // get parameters element
            Node nodeParameters;
            if (create) {
                Node nodeMenu = XMLTool.selectNode(doc1.getDocumentElement(), "/menus");
                nodeParameters = XMLTool.createElement(doc1, (Element) nodeMenu, "parameters");
                nodeMenu.appendChild(nodeParameters);
            } else {
                nodeParameters = XMLTool.selectNode(doc1.getDocumentElement(),
                        "//menuitem[@key=" + key + "]/parameters");
            }

            XMLTool.removeChildNodes((Element) nodeParameters, false);

            if (isArrayFormItem(formItems, "paramname")) {
                String[] paramName = (String[]) formItems.get("paramname");
                String[] paramValue = (String[]) formItems.get("paramval");
                for (int i = 0; i < paramName.length; i++) {
                    final String currParamName = paramName[i];
                    if (currParamName == null || !currParamName.trim().equals("")) {
                        Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter",
                                paramValue[i]);
                        newElem.setAttribute("name", currParamName);
                        nodeParameters.appendChild(newElem);
                    }
                }
            } else {
                // ingen sideparametre finnes, vi lager en
                String paramName = formItems.getString("paramname", "");
                String paramValue = formItems.getString("paramval", "");
                if (paramName.length() > 0) {
                    Element newElem = XMLTool.createElement(doc1, (Element) nodeParameters, "parameter",
                            paramValue);
                    newElem.setAttribute("name", paramName);
                    nodeParameters.appendChild(newElem);
                }
            }
            parameters.put("referer", formItems.getString("referer"));

        }

        if (pageTemplateParamsXML == null) {
            Element nameElem = (Element) XMLTool.selectNode(doc1, "//menuitem[@key = '" + key + "']/page");

            if (nameElem != null) {
                pageTemplateKey = Integer.parseInt(nameElem.getAttribute("pagetemplatekey"));
                pageTemplateParamsXML = admin.getPageTemplParams(pageTemplateKey);
            }
        }

        Document doc8;
        if (pageTemplateParamsXML != null) {
            doc8 = XMLTool.domparse(pageTemplateParamsXML);
            XMLTool.mergeDocuments(doc1, doc8, true);
        }

        String xpath = "/pagetemplates/pagetemplate[@key=" + pageTemplateKey + "]";
        Element pagetemplateElem = (Element) XMLTool.selectNode(pageTemplateDoc, xpath);
        if (pagetemplateElem != null) {
            String pageTemplateType = pagetemplateElem.getAttribute("type");
            if ("form".equals(pageTemplateType)) {
                Element dataElem = XMLTool.getElement(menuitemElem, "data");
                Element formElem = XMLTool.getElement(dataElem, "form");
                if (formElem != null) {
                    String keyStr = formElem.getAttribute("categorykey");
                    if (keyStr.length() > 0) {
                        int categoryKey = Integer.parseInt(keyStr);
                        categoryXML = admin.getCategoryNameXML(categoryKey);
                    }
                }
            }
        }

        if (categoryXML != null) {
            Document doc5 = XMLTool.domparse(categoryXML);
            XMLTool.mergeDocuments(doc1, doc5, true);
        }

        // Get content types for this site
        XMLTool.mergeDocuments(doc1, admin.getContentTypes(false).getAsDOMDocument(), true);

        // Append languages
        Document langs = XMLTool.domparse(admin.getLanguages());
        XMLTool.mergeDocuments(doc1, langs, true);

        DOMSource xmlSource = new DOMSource(doc1);

        // Stylesheet
        Source xslSource = AdminStore.getStylesheet(session, "menu_item_form.xsl");

        // Parameters
        addCommonParameters(admin, user, request, parameters, -1, menuKey);
        parameters.put("page", String.valueOf(request.getParameter("page")));
        if ((key == null || key.length() == 0 || key.equals("none"))) {
            parameters.put("key", "none");
        } else {
            parameters.put("key", key);
        }

        String type = formItems.getString("type", null);
        if ((type == null || "page".equals(type)) && pageTemplateKey >= 0) {
            if (pagetemplateElem != null) {
                type = pagetemplateElem.getAttribute("type");
            }
        }

        if ("document".equals(type) || "form".equals(type)) {
            type = "content";
        }

        parameters.put("type", type);
        parameters.put("insertbelow", formItems.getString("insertbelow", null));
        parameters.put("selpagetemplatekey", String.valueOf(pageTemplateKey));
        parameters.put("name", formItems.getString("name", null));

        if ("on".equals(formItems.getString("visibility", null))) {
            parameters.put("visibility", "on");
        }

        parameters.put("forward_data", formItems.get("forward_data", Boolean.FALSE));
        parameters.put("menu-name", formItems.getString("menu-name", null));
        parameters.put("displayname", formItems.getString("displayname", null));
        parameters.put("description", formItems.getString("description", null));
        parameters.put("keywords", formItems.getString("keywords", null));
        parameters.put("alias", formItems.getString("alias", null));
        parameters.put("document", formItems.getString("contentdata_body", null));
        if (formItems.getString("noauth", null) != null) {
            if ("on".equals(formItems.getString("noauth", null))) {
                parameters.put("noauth", "false");
            } else {
                parameters.put("noauth", "true");
            }
        }
        parameters.put("catselkey", formItems.getString("catsel", null));
        parameters.put("catkey", formItems.getString("category_key", null));
        parameters.put("catname", formItems.getString("viewcategory_key", null));
        parameters.put("menukey", String.valueOf(menuKey));

        // find content title if contentkey is specified
        if (menuitemElem != null) {
            String contentKeyStr = menuitemElem.getAttribute("contentkey");
            if (contentKeyStr.length() > 0) {
                int contentKey = Integer.parseInt(contentKeyStr);
                int versionKey = admin.getCurrentVersionKey(contentKey);
                String contentTitle = admin.getContentTitle(versionKey);
                parameters.put("contenttitle", contentTitle);
            }
        }

        // Adds accessrights values, so that these can be remembered until next page
        for (Object formItemKey : formItems.keySet()) {
            String paramName = (String) formItemKey;
            if (paramName.startsWith("accessright[key=")) {
                parameters.put(paramName, formItems.getString(paramName));
            }
        }
        parameters.put("selectedtabpageid", formItems.getString("selectedtabpageid", null));

        // Get form categories
        int[] contentTypeKeys = admin.getContentTypesByHandlerClass(
                "com.enonic.vertical.adminweb.handlers.ContentFormHandlerServlet");
        if (contentTypeKeys != null && contentTypeKeys.length > 0) {
            StringBuffer contentTypeString = new StringBuffer();
            for (int i = 0; i < contentTypeKeys.length; i++) {
                if (i > 0) {
                    contentTypeString.append(',');
                }
                contentTypeString.append(contentTypeKeys[i]);
            }
            parameters.put("contenttypestring", contentTypeString.toString());
        } else {
            parameters.put("contenttypestring", "99999");
        }

        addAccessLevelParameters(user, parameters);

        UserEntity defaultRunAsUser = siteDao.findByKey(formItems.getInt("menukey")).resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        parameters.put("defaultRunAsUser", defaultRunAsUserName);

        transformXML(session, response.getWriter(), xmlSource, xslSource, parameters);

    } catch (IOException ioe) {
        String msg = "I/O error: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, ioe);
    } catch (TransformerException te) {
        String msg = "XSL transformer error: %t";
        VerticalAdminLogger.errorAdmin(this.getClass(), 0, msg, te);
    }
}

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

protected Document applyChangesInAccessRights(Document docExistingAccessRights,
        Map<String, ExtendedMap> removedAccessRights, Map<String, ExtendedMap> modifiedAccessRights,
        Map<String, ExtendedMap> addedAccessRights) {

    // We have to make a clone of this hashtable, because we may have to remove some elements
    // and we don't want to affect this on the original hashtable.
    addedAccessRights = new HashMap<String, ExtendedMap>(addedAccessRights);

    //("removedAccessRights = " + removedAccessRights);
    //("modifiedAccessRights = " + modifiedAccessRights);
    //("addedAccessRights = " + addedAccessRights);

    Element elExistingAccessRights = docExistingAccessRights.getDocumentElement();

    //("antall accessrights: " + elExistingAccessRights.getChildNodes().getLength());
    // Loop thru existing accessrights and check if there is anyone to remove or modify
    Element curAccessRight = (Element) elExistingAccessRights.getFirstChild();
    while (curAccessRight != null) {

        String groupKey = curAccessRight.getAttribute("groupkey");
        //("checking accessright, groupkey = " + groupKey);

        boolean remove = removedAccessRights.containsKey(groupKey);
        boolean modify = modifiedAccessRights.containsKey(groupKey);
        boolean add = addedAccessRights.containsKey(groupKey);
        boolean overwrite = (modify || add);

        // Remove accessright
        if (remove) {

            //("removing accessright, groupkey = " + groupKey);
            curAccessRight = XMLTool.removeChildFromParent(elExistingAccessRights, curAccessRight);
        }/*w  w w.j a v a 2  s. c o  m*/
        // Overwrite accessright
        else if (overwrite) {

            ExtendedMap params;
            if (modify) {
                params = modifiedAccessRights.get(groupKey);
                //("modifying/overwriting accessright, groupkey = " + groupKey);
            } else // add == true:
            {
                params = addedAccessRights.get(groupKey);
                //("adding/overwriting accessright, groupkey = " + groupKey);
            }

            Document docNewAccessRight = XMLTool.createDocument("foo");
            Element elNewAccessRight = buildAccessRightElement(docNewAccessRight,
                    docNewAccessRight.getDocumentElement(), groupKey, params);

            Element imported = (Element) docExistingAccessRights.importNode(elNewAccessRight, true);
            elExistingAccessRights.replaceChild(imported, curAccessRight);
            curAccessRight = imported;

            // Hvis vi overskriver eksisterende rettighet i stedet for  legge til, fordi den finnes fra fr
            // m vi fjerne rettigheten fra addedAccessRights, slik at vi ikke legger til den to ganger.
            if (add) {
                //("Found an accessright that we wanted to add, that existed - we overwrite it
                // inseated, and removes the groupkey ("+groupKey+")from the addAccessRights hashtable so that it
                // want be added later");
                addedAccessRights.remove(groupKey);
            }

            //
            curAccessRight = (Element) curAccessRight.getNextSibling();
        } else {
            curAccessRight = (Element) curAccessRight.getNextSibling();
        }
    }
    // Add new accessrights
    for (Object addedAccessRightKey : addedAccessRights.keySet()) {
        String currentGroupKey = (String) addedAccessRightKey;

        //("adding new accessright, groupkey = " + currentGroupKey);

        ExtendedMap params = addedAccessRights.get(currentGroupKey);
        Document docNewAccessRight = XMLTool.createDocument("foo");
        Element elNewAccessRight = buildAccessRightElement(docNewAccessRight,
                docNewAccessRight.getDocumentElement(), currentGroupKey, params);

        elExistingAccessRights.appendChild(docExistingAccessRights.importNode(elNewAccessRight, true));
    }

    return docExistingAccessRights;
}

From source file:com.netspective.sparx.util.xml.XmlSource.java

/**
 * Given an element, apply templates to the node. If there is an attribute called "template" then inherit that
 * template first. Then, search through all of the nodes in the element and try to find all <include-template id="x">
 * elements to copy the template elements at those locations. Also, go through each child to see if a tag name
 * exists that matches a template name -- if it does, then "inherit" that template to replace the element at that
 * location.//  w  w  w .j a  v  a2 s.  co m
 */
public void processTemplates(Element elem) {
    inheritNodes(elem, templates, "template", defaultExcludeElementsFromInherit);

    NodeList includes = elem.getElementsByTagName("include-template");
    if (includes != null && includes.getLength() > 0) {
        for (int n = 0; n < includes.getLength(); n++) {
            Element include = (Element) includes.item(n);
            String templateName = include.getAttribute("id");
            Element template = (Element) templates.get(templateName);

            if (template != null) {
                NodeList incChildren = template.getChildNodes();
                for (int c = 0; c < incChildren.getLength(); c++) {
                    Node incCopy = xmlDoc.importNode(incChildren.item(c), true);
                    if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                        ((Element) incCopy).setAttribute("_included-from-template", templateName);
                    elem.insertBefore(incCopy, include);
                }
            }
        }
    }

    NodeList children = elem.getChildNodes();
    for (int c = 0; c < children.getLength(); c++) {
        Node childNode = children.item(c);
        if (childNode.getNodeType() != Node.ELEMENT_NODE)
            continue;

        String nodeName = childNode.getNodeName();
        if (templates.containsKey(nodeName)) {
            Element template = (Element) templates.get(nodeName);
            Node incCopy = xmlDoc.importNode(template, true);
            if (incCopy.getNodeType() == Node.ELEMENT_NODE)
                ((Element) incCopy).setAttribute("_included-from-template", nodeName);

            // make sure that the child's attributes overwrite the attributes in the templates with the same name
            NamedNodeMap attrsInChild = childNode.getAttributes();
            for (int a = 0; a < attrsInChild.getLength(); a++) {
                Node childAttr = attrsInChild.item(a);
                ((Element) incCopy).setAttribute(childAttr.getNodeName(), childAttr.getNodeValue());
            }

            // now do the actual replacement
            inheritNodes((Element) incCopy, templates, "template", defaultExcludeElementsFromInherit);
            elem.replaceChild(incCopy, childNode);
        } else
            inheritNodes((Element) childNode, templates, "template", defaultExcludeElementsFromInherit);
    }
}

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 {/*www  . j av a2 s .  c o  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);
    }
}

From source file:net.wastl.webmail.xml.XMLSystemData.java

public void setConfigRaw(String groupname, String key, String value, String type) {
    String curval = getConfigRaw(key);
    if (curval == null || !curval.equals(value)) {
        log.debug("XMLSystemData: " + groupname + "/" + key + " = " + value);
        /* Find all GROUP elements */
        NodeList groupl = sysdata.getElementsByTagName("GROUP");
        int i = 0;
        for (i = 0; i < groupl.getLength(); i++) {
            Element group = (Element) groupl.item(i);
            if (group.getAttribute("name").equals(groupname)) {
                /* If the group name matches, find all keys */
                NodeList keyl = group.getElementsByTagName("KEY");
                int j = 0;
                for (j = 0; j < keyl.getLength(); j++) {
                    Element keyelem = (Element) keyl.item(j);
                    if (key.equals(XMLCommon.getElementTextValue(keyelem))) {
                        /* If the key already exists, replace it */
                        Element conf = (Element) keyelem.getParentNode();
                        group.replaceChild(createConfigElement(key, value, type), conf);
                        return;
                    }/*from   www.j  a  v  a 2 s  .co m*/
                }
                /* If the key was not found, append it */
                if (j >= keyl.getLength()) {
                    group.appendChild(createConfigElement(key, value, type));
                    return;
                }
            }
        }
        if (i >= groupl.getLength()) {
            Element group = createConfigGroup(groupname);
            group.appendChild(createConfigElement(key, value, type));
        }
    }
}

From source file:org.apache.ws.security.message.TestMessageTransformer.java

public static Element addEncryptedDataWithEmbeddedEncryptedKeyInWsseHeader(Element saaj) {
    moveReferenceList(saaj);/*from w w  w  . j a  v a  2  s  .c o m*/
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);

    Element newEncData = (Element) encData.cloneNode(true);
    String newId = newEncData.getAttributeNS(null, "Id") + "b";
    newEncData.setAttributeNS(null, "Id", newId);

    Element encKey = getFirstChildElement(saaj, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element newEncKey = (Element) encKey.cloneNode(true);
    String newEcId = newEncKey.getAttributeNS(null, "Id") + "b";
    newEncKey.setAttributeNS(null, "Id", newEcId);

    Element keyInfo = getFirstChildElement(newEncData,
            new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo"), true);
    Element str = getFirstChildElement(newEncData,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "SecurityTokenReference"),
            true);
    keyInfo.replaceChild(newEncKey, str);

    Element wsseHeader = getFirstChildElement(saaj,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();

    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    newWsseHeader.appendChild(newEncData);

    Node parent = wsseHeader.getParentNode();
    parent.removeChild(wsseHeader);
    parent.appendChild(newWsseHeader);
    print(saaj.getOwnerDocument());
    return newEncData;

}

From source file:org.dspace.installer_edm.InstallerEDMAskosi.java

/**
 * Modifica el archivo web.xml de Askosi para indicarle el directorio de datos de Askosi
 *
 * @param webXmlFile archivo web.xml de Askosi
 *///w ww.  j a v  a  2  s. c o  m
private void changeWebXml(File webXmlFile, String webXmlFileName) {
    try {
        // se abre con DOM el archivo web.xml
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(webXmlFile);
        XPath xpathInputForms = XPathFactory.newInstance().newXPath();

        // se busca el elemento SKOSdirectory
        NodeList results = (NodeList) xpathInputForms.evaluate("//*[contains(*,\"SKOSdirectory\")]", doc,
                XPathConstants.NODESET);
        if (results.getLength() > 0) {
            Element contextParam = (Element) results.item(0);

            // se busca el elemento context-param como hijo del anterior
            if (contextParam.getTagName().equals("context-param")) {

                // se busca el elemento param-value como hijo del anterior
                NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                if (resultsParamValue.getLength() > 0) {

                    // se modifica con la ruta del directorio de datos de Askosi
                    Element valueParam = (Element) resultsParamValue.item(0);
                    Text text = doc.createTextNode(finalAskosiDataDestDirFile.getAbsolutePath());
                    valueParam.replaceChild(text, valueParam.getFirstChild());

                    // se guarda
                    TransformerFactory transformerFactory = TransformerFactory.newInstance();
                    Transformer transformer = transformerFactory.newTransformer();
                    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
                    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                    //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                    DocumentType docType = doc.getDoctype();
                    if (docType != null) {
                        if (docType.getPublicId() != null)
                            transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, docType.getPublicId());
                        transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, docType.getSystemId());
                    }
                    DOMSource source = new DOMSource(doc);
                    StreamResult result = (fileSeparator.equals("\\")) ? new StreamResult(webXmlFileName)
                            : new StreamResult(webXmlFile);
                    transformer.transform(source, result);
                }
            }
        } else
            installerEDMDisplay.showQuestion(currentStepGlobal, "changeWebXml.noSKOSdirectory",
                    new String[] { webXmlFile.getAbsolutePath() });
    } catch (ParserConfigurationException e) {
        showException(e);
    } catch (SAXException e) {
        showException(e);
    } catch (IOException e) {
        showException(e);
    } catch (XPathExpressionException e) {
        showException(e);
    } catch (TransformerConfigurationException e) {
        showException(e);
    } catch (TransformerException e) {
        showException(e);
    }

}

From source file:org.dspace.installer_edm.InstallerEDMConfEDMExport.java

/**
 * Abre el archivo EDMExport.war y se recorre la lista de archivos que lo componen.
 * En web.xml lo abre con jdom y pide la ruta de dspace.cfg para modificarlo
 * Para los jar con la api de dspace y de lucene muestra cul hay en el war y cul en dspace y pregunta si se cambia
 */// w  ww .  java  2s  . c  o  m
public void configure() {
    try {
        // comprobar validez del war
        if (checkEDMExporWar()) {
            // copiar al directorio de trabajo
            eDMExportWarWorkFile = new File(
                    myInstallerWorkDirPath + fileSeparator + eDMExportWarFile.getName());
            copyDspaceFile2Work(eDMExportWarFile, eDMExportWarWorkFile, "configure.edmexport");

            // abrir el war
            eDMExportWarJarFile = new JarFile(eDMExportWarWorkFile);
            // buscar web.xml
            ZipEntry edmExportWebZipentry = eDMExportWarJarFile.getEntry("WEB-INF/web.xml");
            if (edmExportWebZipentry == null)
                installerEDMDisplay.showQuestion(currentStepGlobal, "configure.notwebxml");
            else {
                // crear dom de web.xml
                InputStream is = eDMExportWarJarFile.getInputStream(edmExportWebZipentry);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                eDMExportDocument = builder.parse(is);
                // buscar dspace-config
                XPath xpathInputForms = XPathFactory.newInstance().newXPath();
                NodeList resultsDspaceConfig = (NodeList) xpathInputForms.evaluate(xpathDspaceConfigTemplate,
                        eDMExportDocument, XPathConstants.NODESET);
                if (resultsDspaceConfig.getLength() == 0) {
                    installerEDMDisplay.showQuestion(currentStepGlobal, "configure.nopath");
                } else {
                    // preguntar ruta de dspace.cfg y configurar los jar
                    Element contextParam = (Element) resultsDspaceConfig.item(0);
                    if (contextParam.getTagName().equals("context-param")) {
                        NodeList resultsParamValue = contextParam.getElementsByTagName("param-value");
                        if (resultsParamValue.getLength() > 0) {
                            Element valueParam = (Element) resultsParamValue.item(0);
                            String dspaceCfg = DspaceDir + "config" + fileSeparator + "dspace.cfg";
                            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg",
                                    new String[] { dspaceCfg });
                            File dspaceCfgFile = new File(dspaceCfg);
                            String response = null;
                            do {
                                response = br.readLine();
                                if (response == null)
                                    continue;
                                response = response.trim();
                                if (response.isEmpty()) {
                                    break;
                                } else {
                                    dspaceCfgFile = new File(response);
                                    if (dspaceCfgFile.exists())
                                        break;
                                }
                            } while (true);
                            Text text = eDMExportDocument.createTextNode(dspaceCfgFile.getAbsolutePath());
                            valueParam.replaceChild(text, valueParam.getFirstChild());
                            // jar con la api de dspace
                            findDspaceApi();
                            // jars con lucene
                            findLuceneLib();
                            // escribir el nuevo war con las modificaciones
                            writeNewJar();
                            eDMExportWarJarFile = new JarFile(eDMExportWarWorkFile);
                            installerEDMDisplay.showLn();
                            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.ok",
                                    new String[] { eDMExportWarWorkFile.getAbsolutePath() });
                        }
                    }
                }
            }
        }
    } catch (IOException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (ParserConfigurationException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (SAXException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (XPathExpressionException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    } catch (TransformerException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.dspacecfg.nok");
    }
}